]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AppUtils.pm
LP1908614: Show the Age Hold Protection name in the staff catalog
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 use strict; use warnings;
3 use MARC::Record;
4 use MARC::File::XML (BinaryEncoding => 'utf8', RecordFormat => 'USMARC');
5 use OpenILS::Application;
6 use base qw/OpenILS::Application/;
7 use OpenSRF::Utils::Cache;
8 use OpenSRF::Utils::Logger qw/$logger/;
9 use OpenILS::Utils::ModsParser;
10 use OpenSRF::EX qw(:try);
11 use OpenILS::Event;
12 use Data::Dumper;
13 use OpenILS::Utils::CStoreEditor;
14 use OpenILS::Const qw/:const/;
15 use Unicode::Normalize;
16 use OpenSRF::Utils::SettingsClient;
17 use UUID::Tiny;
18 use Encode;
19 use DateTime;
20 use DateTime::Format::ISO8601;
21 use List::MoreUtils qw/uniq/;
22 use Digest::MD5 qw(md5_hex);
23
24 # ---------------------------------------------------------------------------
25 # Pile of utilty methods used accross applications.
26 # ---------------------------------------------------------------------------
27 my $cache_client = "OpenSRF::Utils::Cache";
28 my $MARC_NAMESPACE = 'http://www.loc.gov/MARC21/slim';
29
30 # ---------------------------------------------------------------------------
31 # on sucess, returns the created session, on failure throws ERROR exception
32 # ---------------------------------------------------------------------------
33 sub start_db_session {
34
35     my $self = shift;
36     my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
37     my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
38
39     my $trans_resp = $trans_req->recv();
40     if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
41     if( ! $trans_resp->content() ) {
42         throw OpenSRF::ERROR 
43             ("Unable to Begin Transaction with database" );
44     }
45     $trans_req->finish();
46
47     $logger->debug("Setting global storage session to ".
48         "session: " . $session->session_id . " : " . $session->app );
49
50     return $session;
51 }
52
53 sub set_audit_info {
54     my $self = shift;
55     my $session = shift;
56     my $authtoken = shift;
57     my $user_id = shift;
58     my $ws_id = shift;
59     
60     my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
61     my $audit_resp = $audit_req->recv();
62     $audit_req->finish();
63 }
64
65 my $PERM_QUERY = {
66     select => {
67         au => [ {
68             transform => 'permission.usr_has_perm',
69             alias => 'has_perm',
70             column => 'id',
71             params => []
72         } ]
73     },
74     from => 'au',
75     where => {},
76 };
77
78
79 # returns undef if user has all of the perms provided
80 # returns the first failed perm on failure
81 sub check_user_perms {
82     my($self, $user_id, $org_id, @perm_types ) = @_;
83     $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
84
85     for my $type (@perm_types) {
86         $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
87         $PERM_QUERY->{where}->{id} = $user_id;
88         return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
89     }
90     return undef;
91 }
92
93 # checks the list of user perms.  The first one that fails returns a new
94 sub check_perms {
95     my( $self, $user_id, $org_id, @perm_types ) = @_;
96     my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
97     return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
98     return undef;
99 }
100
101
102
103 # ---------------------------------------------------------------------------
104 # commits and destroys the session
105 # ---------------------------------------------------------------------------
106 sub commit_db_session {
107     my( $self, $session ) = @_;
108
109     my $req = $session->request( "open-ils.storage.transaction.commit" );
110     my $resp = $req->recv();
111
112     if(!$resp) {
113         throw OpenSRF::EX::ERROR ("Unable to commit db session");
114     }
115
116     if(UNIVERSAL::isa($resp,"Error")) { 
117         throw $resp ($resp->stringify); 
118     }
119
120     if(!$resp->content) {
121         throw OpenSRF::EX::ERROR ("Unable to commit db session");
122     }
123
124     $session->finish();
125     $session->disconnect();
126     $session->kill_me();
127 }
128
129 sub rollback_db_session {
130     my( $self, $session ) = @_;
131
132     my $req = $session->request("open-ils.storage.transaction.rollback");
133     my $resp = $req->recv();
134     if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
135
136     $session->finish();
137     $session->disconnect();
138     $session->kill_me();
139 }
140
141
142 # returns undef it the event is not an ILS event
143 # returns the event code otherwise
144 sub event_code {
145     my( $self, $evt ) = @_;
146     return $evt->{ilsevent} if $self->is_event($evt);
147     return undef;
148 }
149
150 # some events, in particular auto-generated events, don't have an 
151 # ilsevent key.  treat hashes with a 'textcode' key as events.
152 sub is_event {
153     my ($self, $evt) = @_;
154     return (
155         ref($evt) eq 'HASH' and (
156             defined $evt->{ilsevent} or
157             defined $evt->{textcode}
158         )
159     );
160 }
161
162 # ---------------------------------------------------------------------------
163 # Checks to see if a user is logged in.  Returns the user record on success,
164 # throws an exception on error.
165 # ---------------------------------------------------------------------------
166 sub check_user_session {
167     my( $self, $user_session ) = @_;
168
169     my $content = $self->simplereq( 
170         'open-ils.auth', 
171         'open-ils.auth.session.retrieve', $user_session);
172
173     return undef if (!$content) or $self->event_code($content);
174     return $content;
175 }
176
177 # generic simple request returning a scalar value
178 sub simplereq {
179     my($self, $service, $method, @params) = @_;
180     return $self->simple_scalar_request($service, $method, @params);
181 }
182
183
184 sub simple_scalar_request {
185     my($self, $service, $method, @params) = @_;
186
187     my $session = OpenSRF::AppSession->create( $service );
188
189     my $request = $session->request( $method, @params );
190
191     my $val;
192     my $err;
193     try  {
194
195         $val = $request->gather(1); 
196
197     } catch Error with {
198         $err = shift;
199     };
200
201     if( $err ) {
202         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
203         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
204     }
205
206     return $val;
207 }
208
209 sub build_org_tree {
210     my( $self, $orglist ) = @_;
211
212     return $orglist unless ref $orglist; 
213     return $$orglist[0] if @$orglist == 1;
214
215     my @list = sort { 
216         $a->ou_type <=> $b->ou_type ||
217         $a->name cmp $b->name } @$orglist;
218
219     for my $org (@list) {
220
221         next unless ($org);
222         next if (!defined($org->parent_ou) || $org->parent_ou eq "");
223
224         my ($parent) = grep { $_->id == $org->parent_ou } @list;
225         next unless $parent;
226         $parent->children([]) unless defined($parent->children); 
227         push( @{$parent->children}, $org );
228     }
229
230     return $list[0];
231 }
232
233 sub fetch_closed_date {
234     my( $self, $cd ) = @_;
235     my $evt;
236     
237     $logger->debug("Fetching closed_date $cd from cstore");
238
239     my $cd_obj = $self->simplereq(
240         'open-ils.cstore',
241         'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
242
243     if(!$cd_obj) {
244         $logger->info("closed_date $cd not found in the db");
245         $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
246     }
247
248     return ($cd_obj, $evt);
249 }
250
251 sub fetch_user {
252     my( $self, $userid ) = @_;
253     my( $user, $evt );
254     
255     $logger->debug("Fetching user $userid from cstore");
256
257     $user = $self->simplereq(
258         'open-ils.cstore',
259         'open-ils.cstore.direct.actor.user.retrieve', $userid );
260
261     if(!$user) {
262         $logger->info("User $userid not found in the db");
263         $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
264     }
265
266     return ($user, $evt);
267 }
268
269 sub checkses {
270     my( $self, $session ) = @_;
271     my $user = $self->check_user_session($session) or 
272         return (undef, OpenILS::Event->new('NO_SESSION'));
273     return ($user);
274 }
275
276
277 # verifiese the session and checks the permissions agains the
278 # session user and the user's home_ou as the org id
279 sub checksesperm {
280     my( $self, $session, @perms ) = @_;
281     my $user; my $evt; my $e; 
282     $logger->debug("Checking user session $session and perms @perms");
283     ($user, $evt) = $self->checkses($session);
284     return (undef, $evt) if $evt;
285     $evt = $self->check_perms($user->id, $user->home_ou, @perms);
286     return ($user, $evt);
287 }
288
289
290 sub checkrequestor {
291     my( $self, $staffobj, $userid, @perms ) = @_;
292     my $user; my $evt;
293     $userid = $staffobj->id unless defined $userid;
294
295     $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
296
297     if( $userid ne $staffobj->id ) {
298         ($user, $evt) = $self->fetch_user($userid);
299         return (undef, $evt) if $evt;
300         $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
301
302     } else {
303         $user = $staffobj;
304     }
305
306     return ($user, $evt);
307 }
308
309 sub checkses_requestor {
310     my( $self, $authtoken, $targetid, @perms ) = @_;
311     my( $requestor, $target, $evt );
312
313     ($requestor, $evt) = $self->checkses($authtoken);
314     return (undef, undef, $evt) if $evt;
315
316     ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
317     return( $requestor, $target, $evt);
318 }
319
320 sub fetch_copy {
321     my( $self, $copyid ) = @_;
322     my( $copy, $evt );
323
324     $logger->debug("Fetching copy $copyid from cstore");
325
326     $copy = $self->simplereq(
327         'open-ils.cstore',
328         'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
329
330     if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
331
332     return( $copy, $evt );
333 }
334
335
336 # retrieves a circ object by id
337 sub fetch_circulation {
338     my( $self, $circid ) = @_;
339     my $circ; my $evt;
340     
341     $logger->debug("Fetching circ $circid from cstore");
342
343     $circ = $self->simplereq(
344         'open-ils.cstore',
345         "open-ils.cstore.direct.action.circulation.retrieve", $circid );
346
347     if(!$circ) {
348         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
349     }
350
351     return ( $circ, $evt );
352 }
353
354 sub fetch_record_by_copy {
355     my( $self, $copyid ) = @_;
356     my( $record, $evt );
357
358     $logger->debug("Fetching record by copy $copyid from cstore");
359
360     $record = $self->simplereq(
361         'open-ils.cstore',
362         'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
363         { flesh => 3,
364           flesh_fields => { bre => [ 'fixed_fields' ],
365                     acn => [ 'record' ],
366                     acp => [ 'call_number' ],
367                   }
368         }
369     );
370
371     if(!$record) {
372         $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
373     } else {
374         $record = $record->call_number->record;
375     }
376
377     return ($record, $evt);
378 }
379
380 # turns a record object into an mvr (mods) object
381 sub record_to_mvr {
382     my( $self, $record ) = @_;
383     return undef unless $record and $record->marc;
384     my $u = OpenILS::Utils::ModsParser->new();
385     $u->start_mods_batch( $record->marc );
386     my $mods = $u->finish_mods_batch();
387     $mods->doc_id($record->id);
388    $mods->tcn($record->tcn_value);
389     return $mods;
390 }
391
392 sub fetch_hold {
393     my( $self, $holdid ) = @_;
394     my( $hold, $evt );
395
396     $logger->debug("Fetching hold $holdid from cstore");
397
398     $hold = $self->simplereq(
399         'open-ils.cstore',
400         'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
401
402     $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
403
404     return ($hold, $evt);
405 }
406
407
408 sub fetch_hold_transit_by_hold {
409     my( $self, $holdid ) = @_;
410     my( $transit, $evt );
411
412     $logger->debug("Fetching transit by hold $holdid from cstore");
413
414     $transit = $self->simplereq(
415         'open-ils.cstore',
416         'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid, cancel_time => undef } );
417
418     $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
419
420     return ($transit, $evt );
421 }
422
423 # fetches the captured, but not fulfilled hold attached to a given copy
424 sub fetch_open_hold_by_copy {
425     my( $self, $copyid ) = @_;
426     $logger->debug("Searching for active hold for copy $copyid");
427     my( $hold, $evt );
428
429     $hold = $self->cstorereq(
430         'open-ils.cstore.direct.action.hold_request.search',
431         { 
432             current_copy        => $copyid , 
433             capture_time        => { "!=" => undef }, 
434             fulfillment_time    => undef,
435             cancel_time         => undef,
436         } );
437
438     $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
439     return ($hold, $evt);
440 }
441
442 sub fetch_hold_transit {
443     my( $self, $transid ) = @_;
444     my( $htransit, $evt );
445     $logger->debug("Fetching hold transit with hold id $transid");
446     $htransit = $self->cstorereq(
447         'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
448     $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
449     return ($htransit, $evt);
450 }
451
452 sub fetch_copy_by_barcode {
453     my( $self, $barcode ) = @_;
454     my( $copy, $evt );
455
456     $logger->debug("Fetching copy by barcode $barcode from cstore");
457
458     $copy = $self->simplereq( 'open-ils.cstore',
459         'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
460         #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
461
462     $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
463
464     return ($copy, $evt);
465 }
466
467 sub fetch_open_billable_transaction {
468     my( $self, $transid ) = @_;
469     my( $transaction, $evt );
470
471     $logger->debug("Fetching open billable transaction $transid from cstore");
472
473     $transaction = $self->simplereq(
474         'open-ils.cstore',
475         'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
476
477     $evt = OpenILS::Event->new(
478         'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
479
480     return ($transaction, $evt);
481 }
482
483
484
485 my %buckets;
486 $buckets{'biblio'} = 'biblio_record_entry_bucket';
487 $buckets{'callnumber'} = 'call_number_bucket';
488 $buckets{'copy'} = 'copy_bucket';
489 $buckets{'user'} = 'user_bucket';
490
491 sub fetch_container {
492     my( $self, $id, $type ) = @_;
493     my( $bucket, $evt );
494
495     $logger->debug("Fetching container $id with type $type");
496
497     my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
498     $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
499     $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
500     $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
501
502     my $meth = $buckets{$type};
503     $bucket = $self->simplereq(
504         'open-ils.cstore',
505         "open-ils.cstore.direct.container.$meth.retrieve", $id );
506
507     $evt = OpenILS::Event->new(
508         $e, container => $id, container_type => $type ) unless $bucket;
509
510     return ($bucket, $evt);
511 }
512
513
514 sub fetch_container_e {
515     my( $self, $editor, $id, $type ) = @_;
516
517     my( $bucket, $evt );
518     $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
519     $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
520     $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
521     $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
522
523     $evt = $editor->event unless $bucket;
524     return ($bucket, $evt);
525 }
526
527 sub fetch_container_item_e {
528     my( $self, $editor, $id, $type ) = @_;
529
530     my( $bucket, $evt );
531     $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
532     $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
533     $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
534     $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
535
536     $evt = $editor->event unless $bucket;
537     return ($bucket, $evt);
538 }
539
540
541
542
543
544 sub fetch_container_item {
545     my( $self, $id, $type ) = @_;
546     my( $bucket, $evt );
547
548     $logger->debug("Fetching container item $id with type $type");
549
550     my $meth = $buckets{$type} . "_item";
551
552     $bucket = $self->simplereq(
553         'open-ils.cstore',
554         "open-ils.cstore.direct.container.$meth.retrieve", $id );
555
556
557     my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
558     $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
559     $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
560     $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
561
562     $evt = OpenILS::Event->new(
563         $e, itemid => $id, container_type => $type ) unless $bucket;
564
565     return ($bucket, $evt);
566 }
567
568
569 sub fetch_patron_standings {
570     my $self = shift;
571     $logger->debug("Fetching patron standings");    
572     return $self->simplereq(
573         'open-ils.cstore', 
574         'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
575 }
576
577
578 sub fetch_permission_group_tree {
579     my $self = shift;
580     $logger->debug("Fetching patron profiles"); 
581     return $self->simplereq(
582         'open-ils.actor', 
583         'open-ils.actor.groups.tree.retrieve' );
584 }
585
586 sub fetch_permission_group_descendants {
587     my( $self, $profile ) = @_;
588     my $group_tree = $self->fetch_permission_group_tree();
589     my $start_here;
590     my @groups;
591
592     # FIXME: okay, so it's not an org tree, but it is compatible
593     $self->walk_org_tree($group_tree, sub {
594         my $g = shift;
595         if ($g->id == $profile) {
596             $start_here = $g;
597         }
598     });
599
600     $self->walk_org_tree($start_here, sub {
601         my $g = shift;
602         push(@groups,$g->id);
603     });
604
605     return \@groups;
606 }
607
608 sub fetch_patron_circ_summary {
609     my( $self, $userid ) = @_;
610     $logger->debug("Fetching patron summary for $userid");
611     my $summary = $self->simplereq(
612         'open-ils.storage', 
613         "open-ils.storage.action.circulation.patron_summary", $userid );
614
615     if( $summary ) {
616         $summary->[0] ||= 0;
617         $summary->[1] ||= 0.0;
618         return $summary;
619     }
620     return undef;
621 }
622
623
624 sub fetch_copy_statuses {
625     my( $self ) = @_;
626     $logger->debug("Fetching copy statuses");
627     return $self->simplereq(
628         'open-ils.cstore', 
629         'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
630 }
631
632 sub fetch_copy_location {
633     my( $self, $id ) = @_;
634     my $evt;
635     my $cl = $self->cstorereq(
636         'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
637     $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
638     return ($cl, $evt);
639 }
640
641 sub fetch_copy_locations {
642     my $self = shift; 
643     return $self->simplereq(
644         'open-ils.cstore', 
645         'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef }, deleted => 'f' });
646 }
647
648 sub fetch_copy_location_by_name {
649     my( $self, $name, $org ) = @_;
650     my $evt;
651     my $cl = $self->cstorereq(
652         'open-ils.cstore.direct.asset.copy_location.search',
653             { name => $name, owning_lib => $org, deleted => 'f' } );
654     $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
655     return ($cl, $evt);
656 }
657
658 sub fetch_callnumber {
659     my( $self, $id, $flesh, $e ) = @_;
660
661     $e ||= OpenILS::Utils::CStoreEditor->new;
662
663     my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
664     return( undef, $evt ) unless $id;
665
666     $logger->debug("Fetching callnumber $id");
667
668     my $cn = $e->retrieve_asset_call_number([
669         $id,
670         { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
671     ]);
672
673     return ( $cn, $e->event );
674 }
675
676 my %ORG_CACHE; # - these rarely change, so cache them..
677 sub fetch_org_unit {
678     my( $self, $id ) = @_;
679     return undef unless $id;
680     return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
681     return $ORG_CACHE{$id} if $ORG_CACHE{$id};
682     $logger->debug("Fetching org unit $id");
683     my $evt = undef;
684
685     my $org = $self->simplereq(
686         'open-ils.cstore', 
687         'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
688     $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
689     $ORG_CACHE{$id}  = $org;
690
691     return ($org, $evt);
692 }
693
694 sub fetch_stat_cat {
695     my( $self, $type, $id ) = @_;
696     my( $cat, $evt );
697     $logger->debug("Fetching $type stat cat: $id");
698     $cat = $self->simplereq(
699         'open-ils.cstore', 
700         "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
701
702     my $e = 'ASSET_STAT_CAT_NOT_FOUND';
703     $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
704
705     $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
706     return ( $cat, $evt );
707 }
708
709 sub fetch_stat_cat_entry {
710     my( $self, $type, $id ) = @_;
711     my( $entry, $evt );
712     $logger->debug("Fetching $type stat cat entry: $id");
713     $entry = $self->simplereq(
714         'open-ils.cstore', 
715         "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
716
717     my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
718     $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
719
720     $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
721     return ( $entry, $evt );
722 }
723
724 sub fetch_stat_cat_entry_default {
725     my( $self, $type, $id ) = @_;
726     my( $entry_default, $evt );
727     $logger->debug("Fetching $type stat cat entry default: $id");
728     $entry_default = $self->simplereq(
729         'open-ils.cstore', 
730         "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
731
732     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
733     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
734
735     $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
736     return ( $entry_default, $evt );
737 }
738
739 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
740     my( $self, $type, $stat_cat, $orgId ) = @_;
741     my $entry_default;
742     $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
743     $entry_default = $self->simplereq(
744         'open-ils.cstore', 
745         "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic", 
746         { stat_cat => $stat_cat, owner => $orgId } );
747
748     $entry_default = $entry_default->[0];
749     return ($entry_default, undef) if $entry_default;
750
751     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
752     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
753     return (undef, OpenILS::Event->new($e) );
754 }
755
756 sub find_org {
757     my( $self, $org_tree, $orgid )  = @_;
758     return undef unless $org_tree and defined $orgid;
759     return $org_tree if ( $org_tree->id eq $orgid );
760     return undef unless ref($org_tree->children);
761     for my $c (@{$org_tree->children}) {
762         my $o = $self->find_org($c, $orgid);
763         return $o if $o;
764     }
765     return undef;
766 }
767
768 sub find_org_by_shortname {
769     my( $self, $org_tree, $shortname )  = @_;
770     return undef unless $org_tree and defined $shortname;
771     return $org_tree if ( $org_tree->shortname eq $shortname );
772     return undef unless ref($org_tree->children);
773     for my $c (@{$org_tree->children}) {
774         my $o = $self->find_org_by_shortname($c, $shortname);
775         return $o if $o;
776     }
777     return undef;
778 }
779
780 sub find_lasso_by_name {
781     my( $self, $name )  = @_;
782     return $self->simplereq(
783         'open-ils.cstore', 
784         'open-ils.cstore.direct.actor.org_lasso.search.atomic', { name => $name } )->[0];
785 }
786
787 sub fetch_lasso_org_maps {
788     my( $self, $lasso )  = @_;
789     return $self->simplereq(
790         'open-ils.cstore', 
791         'open-ils.cstore.direct.actor.org_lasso_map.search.atomic', { lasso => $lasso } );
792 }
793
794 sub fetch_non_cat_type_by_name_and_org {
795     my( $self, $name, $orgId ) = @_;
796     $logger->debug("Fetching non cat type $name at org $orgId");
797     my $types = $self->simplereq(
798         'open-ils.cstore',
799         'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
800         { name => $name, owning_lib => $orgId } );
801     return ($types->[0], undef) if($types and @$types);
802     return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
803 }
804
805 sub fetch_non_cat_type {
806     my( $self, $id ) = @_;
807     $logger->debug("Fetching non cat type $id");
808     my( $type, $evt );
809     $type = $self->simplereq(
810         'open-ils.cstore', 
811         'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
812     $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
813     return ($type, $evt);
814 }
815
816 sub DB_UPDATE_FAILED { 
817     my( $self, $payload ) = @_;
818     return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
819         payload => ($payload) ? $payload : undef ); 
820 }
821
822 sub fetch_booking_reservation {
823     my( $self, $id ) = @_;
824     my( $res, $evt );
825
826     $res = $self->simplereq(
827         'open-ils.cstore', 
828         'open-ils.cstore.direct.booking.reservation.retrieve', $id
829     );
830
831     # simplereq doesn't know how to flesh so ...
832     if ($res) {
833         $res->usr(
834             $self->simplereq(
835                 'open-ils.cstore', 
836                 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
837             )
838         );
839
840         $res->target_resource_type(
841             $self->simplereq(
842                 'open-ils.cstore', 
843                 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
844             )
845         );
846
847         if ($res->current_resource) {
848             $res->current_resource(
849                 $self->simplereq(
850                     'open-ils.cstore', 
851                     'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
852                 )
853             );
854
855             if ($self->is_true( $res->target_resource_type->catalog_item )) {
856                 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
857             }
858         }
859
860         if ($res->target_resource) {
861             $res->target_resource(
862                 $self->simplereq(
863                     'open-ils.cstore', 
864                     'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
865                 )
866             );
867
868             if ($self->is_true( $res->target_resource_type->catalog_item )) {
869                 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
870             }
871         }
872
873     } else {
874         $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
875     }
876
877     return ($res, $evt);
878 }
879
880 sub fetch_circ_duration_by_name {
881     my( $self, $name ) = @_;
882     my( $dur, $evt );
883     $dur = $self->simplereq(
884         'open-ils.cstore', 
885         'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
886     $dur = $dur->[0];
887     $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
888     return ($dur, $evt);
889 }
890
891 sub fetch_recurring_fine_by_name {
892     my( $self, $name ) = @_;
893     my( $obj, $evt );
894     $obj = $self->simplereq(
895         'open-ils.cstore', 
896         'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
897     $obj = $obj->[0];
898     $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
899     return ($obj, $evt);
900 }
901
902 sub fetch_max_fine_by_name {
903     my( $self, $name ) = @_;
904     my( $obj, $evt );
905     $obj = $self->simplereq(
906         'open-ils.cstore', 
907         'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
908     $obj = $obj->[0];
909     $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
910     return ($obj, $evt);
911 }
912
913 sub fetch_hard_due_date_by_name {
914     my( $self, $name ) = @_;
915     my( $obj, $evt );
916     $obj = $self->simplereq(
917         'open-ils.cstore', 
918         'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
919     $obj = $obj->[0];
920     $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
921     return ($obj, $evt);
922 }
923
924 sub storagereq {
925     my( $self, $method, @params ) = @_;
926     return $self->simplereq(
927         'open-ils.storage', $method, @params );
928 }
929
930 sub storagereq_xact {
931     my($self, $method, @params) = @_;
932     my $ses = $self->start_db_session();
933     my $val = $ses->request($method, @params)->gather(1);
934     $self->rollback_db_session($ses);
935     return $val;
936 }
937
938 sub cstorereq {
939     my( $self, $method, @params ) = @_;
940     return $self->simplereq(
941         'open-ils.cstore', $method, @params );
942 }
943
944 sub event_equals {
945     my( $self, $e, $name ) =  @_;
946     if( $e and ref($e) eq 'HASH' and 
947         defined($e->{textcode}) and $e->{textcode} eq $name ) {
948         return 1 ;
949     }
950     return 0;
951 }
952
953 sub logmark {
954     my( undef, $f, $l ) = caller(0);
955     my( undef, undef, undef, $s ) = caller(1);
956     $s =~ s/.*:://g;
957     $f =~ s/.*\///g;
958     $logger->debug("LOGMARK: $f:$l:$s");
959 }
960
961 # takes a copy id 
962 sub fetch_open_circulation {
963     my( $self, $cid ) = @_;
964     $self->logmark;
965
966     my $e = OpenILS::Utils::CStoreEditor->new;
967     my $circ = $e->search_action_circulation({
968         target_copy => $cid, 
969         stop_fines_time => undef, 
970         checkin_time => undef
971     })->[0];
972     
973     return ($circ, $e->event);
974 }
975
976 my $copy_statuses;
977 sub copy_status_from_name {
978     my( $self, $name ) = @_;
979     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
980     for my $status (@$copy_statuses) { 
981         return $status if( $status->name =~ /$name/i );
982     }
983     return undef;
984 }
985
986 sub copy_status_to_name {
987     my( $self, $sid ) = @_;
988     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
989     for my $status (@$copy_statuses) { 
990         return $status->name if( $status->id == $sid );
991     }
992     return undef;
993 }
994
995
996 sub copy_status {
997     my( $self, $arg ) = @_;
998     return $arg if ref $arg;
999     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1000     my ($stat) = grep { $_->id == $arg } @$copy_statuses;
1001     return $stat;
1002 }
1003
1004 sub fetch_open_transit_by_copy {
1005     my( $self, $copyid ) = @_;
1006     my($transit, $evt);
1007     $transit = $self->cstorereq(
1008         'open-ils.cstore.direct.action.transit_copy.search',
1009         { target_copy => $copyid, dest_recv_time => undef, cancel_time => undef });
1010     $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
1011     return ($transit, $evt);
1012 }
1013
1014 sub unflesh_copy {
1015     my( $self, $copy ) = @_;
1016     return undef unless $copy;
1017     $copy->status( $copy->status->id ) if ref($copy->status);
1018     $copy->location( $copy->location->id ) if ref($copy->location);
1019     $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1020     return $copy;
1021 }
1022
1023 sub unflesh_reservation {
1024     my( $self, $reservation ) = @_;
1025     return undef unless $reservation;
1026     $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1027     $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1028     $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1029     $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1030     return $reservation;
1031 }
1032
1033 # un-fleshes a copy and updates it in the DB
1034 # returns a DB_UPDATE_FAILED event on error
1035 # returns undef on success
1036 sub update_copy {
1037     my( $self, %params ) = @_;
1038
1039     my $copy        = $params{copy} || die "update_copy(): copy required";
1040     my $editor  = $params{editor} || die "update_copy(): copy editor required";
1041     my $session = $params{session};
1042
1043     $logger->debug("Updating copy in the database: " . $copy->id);
1044
1045     $self->unflesh_copy($copy);
1046     $copy->editor( $editor );
1047     $copy->edit_date( 'now' );
1048
1049     my $s;
1050     my $meth = 'open-ils.storage.direct.asset.copy.update';
1051
1052     $s = $session->request( $meth, $copy )->gather(1) if $session;
1053     $s = $self->storagereq( $meth, $copy ) unless $session;
1054
1055     $logger->debug("Update of copy ".$copy->id." returned: $s");
1056
1057     return $self->DB_UPDATE_FAILED($copy) unless $s;
1058     return undef;
1059 }
1060
1061 sub update_reservation {
1062     my( $self, %params ) = @_;
1063
1064     my $reservation = $params{reservation}  || die "update_reservation(): reservation required";
1065     my $editor      = $params{editor} || die "update_reservation(): copy editor required";
1066     my $session     = $params{session};
1067
1068     $logger->debug("Updating copy in the database: " . $reservation->id);
1069
1070     $self->unflesh_reservation($reservation);
1071
1072     my $s;
1073     my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1074
1075     $s = $session->request( $meth, $reservation )->gather(1) if $session;
1076     $s = $self->cstorereq( $meth, $reservation ) unless $session;
1077
1078     $logger->debug("Update of copy ".$reservation->id." returned: $s");
1079
1080     return $self->DB_UPDATE_FAILED($reservation) unless $s;
1081     return undef;
1082 }
1083
1084 sub fetch_billable_xact {
1085     my( $self, $id ) = @_;
1086     my($xact, $evt);
1087     $logger->debug("Fetching billable transaction %id");
1088     $xact = $self->cstorereq(
1089         'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1090     $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1091     return ($xact, $evt);
1092 }
1093
1094 sub fetch_billable_xact_summary {
1095     my( $self, $id ) = @_;
1096     my($xact, $evt);
1097     $logger->debug("Fetching billable transaction summary %id");
1098     $xact = $self->cstorereq(
1099         'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1100     $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1101     return ($xact, $evt);
1102 }
1103
1104 sub fetch_fleshed_copy {
1105     my( $self, $id ) = @_;
1106     my( $copy, $evt );
1107     $logger->info("Fetching fleshed copy $id");
1108     $copy = $self->cstorereq(
1109         "open-ils.cstore.direct.asset.copy.retrieve", $id,
1110         { flesh => 1,
1111           flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1112         }
1113     );
1114     $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1115     return ($copy, $evt);
1116 }
1117
1118
1119 # returns the org that owns the callnumber that the copy
1120 # is attached to
1121 sub fetch_copy_owner {
1122     my( $self, $copyid ) = @_;
1123     my( $copy, $cn, $evt );
1124     $logger->debug("Fetching copy owner $copyid");
1125     ($copy, $evt) = $self->fetch_copy($copyid);
1126     return (undef,$evt) if $evt;
1127     ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1128     return (undef,$evt) if $evt;
1129     return ($cn->owning_lib);
1130 }
1131
1132 sub fetch_copy_note {
1133     my( $self, $id ) = @_;
1134     my( $note, $evt );
1135     $logger->debug("Fetching copy note $id");
1136     $note = $self->cstorereq(
1137         'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1138     $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1139     return ($note, $evt);
1140 }
1141
1142 sub fetch_call_numbers_by_title {
1143     my( $self, $titleid ) = @_;
1144     $logger->info("Fetching call numbers by title $titleid");
1145     return $self->cstorereq(
1146         'open-ils.cstore.direct.asset.call_number.search.atomic', 
1147         { record => $titleid, deleted => 'f' });
1148         #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1149 }
1150
1151 sub fetch_copies_by_call_number {
1152     my( $self, $cnid ) = @_;
1153     $logger->info("Fetching copies by call number $cnid");
1154     return $self->cstorereq(
1155         'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1156         #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1157 }
1158
1159 sub fetch_user_by_barcode {
1160     my( $self, $bc ) = @_;
1161     my $cardid = $self->cstorereq(
1162         'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1163     return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1164     my $user = $self->cstorereq(
1165         'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1166     return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1167     return ($user);
1168     
1169 }
1170
1171 sub fetch_bill {
1172     my( $self, $billid ) = @_;
1173     $logger->debug("Fetching billing $billid");
1174     my $bill = $self->cstorereq(
1175         'open-ils.cstore.direct.money.billing.retrieve', $billid );
1176     my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1177     return($bill, $evt);
1178 }
1179
1180 sub walk_org_tree {
1181     my( $self, $node, $callback ) = @_;
1182     return unless $node;
1183     $callback->($node);
1184     if( $node->children ) {
1185         $self->walk_org_tree($_, $callback) for @{$node->children};
1186     }
1187 }
1188
1189 sub is_true {
1190     my( $self, $item ) = @_;
1191     return 1 if $item and $item !~ /^f$/i;
1192     return 0;
1193 }
1194
1195
1196 sub patientreq {
1197     my ($self, $client, $service, $method, @params) = @_;
1198     my ($response, $err);
1199
1200     my $session = create OpenSRF::AppSession($service);
1201     my $request = $session->request($method, @params);
1202
1203     my $spurt = 10;
1204     my $give_up = time + 1000;
1205
1206     try {
1207         while (time < $give_up) {
1208             $response = $request->recv("timeout" => $spurt);
1209             last if $request->complete;
1210
1211             $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1212         }
1213     } catch Error with {
1214         $err = shift;
1215     };
1216
1217     if ($err) {
1218         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1219         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1220     }
1221
1222     return $response->content;
1223 }
1224
1225 # This logic now lives in storage
1226 sub __patron_money_owed {
1227     my( $self, $patronid ) = @_;
1228     my $ses = OpenSRF::AppSession->create('open-ils.storage');
1229     my $req = $ses->request(
1230         'open-ils.storage.money.billable_transaction.summary.search',
1231         { usr => $patronid, xact_finish => undef } );
1232
1233     my $total = 0;
1234     my $data;
1235     while( $data = $req->recv ) {
1236         $data = $data->content;
1237         $total += $data->balance_owed;
1238     }
1239     return $total;
1240 }
1241
1242 sub patron_money_owed {
1243     my( $self, $userid ) = @_;
1244     my $ses = $self->start_db_session();
1245     my $val = $ses->request(
1246         'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1247     $self->rollback_db_session($ses);
1248     return $val;
1249 }
1250
1251 sub patron_total_items_out {
1252     my( $self, $userid ) = @_;
1253     my $ses = $self->start_db_session();
1254     my $val = $ses->request(
1255         'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1256     $self->rollback_db_session($ses);
1257     return $val;
1258 }
1259
1260
1261
1262
1263 #---------------------------------------------------------------------
1264 # Returns  ($summary, $event) 
1265 #---------------------------------------------------------------------
1266 sub fetch_mbts {
1267     my $self = shift;
1268     my $id  = shift;
1269     my $e = shift || OpenILS::Utils::CStoreEditor->new;
1270     $id = $id->id if ref($id);
1271     
1272     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1273         or return (undef, $e->event);
1274
1275     return ($xact);
1276 }
1277
1278
1279 #---------------------------------------------------------------------
1280 # Given a list of money.billable_transaction objects, this creates
1281 # transaction summary objects for each
1282 #--------------------------------------------------------------------
1283 sub make_mbts {
1284     my $self = shift;
1285     my $e = shift;
1286     my @xacts = @_;
1287     return () if (!@xacts);
1288     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1289 }
1290         
1291         
1292 sub ou_ancestor_setting_value {
1293     my($self, $org_id, $name, $e) = @_;
1294     $e = $e || OpenILS::Utils::CStoreEditor->new;
1295     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1296     return $set->{value} if $set;
1297     return undef;
1298 }
1299
1300
1301 # If an authentication token is provided AND this org unit setting has a
1302 # view_perm, then make sure the user referenced by the auth token has
1303 # that permission.  This means that if you call this method without an
1304 # authtoken param, you can get whatever org unit setting values you want.
1305 # API users beware.
1306 #
1307 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1308 # authtoken is checked, but the $auth arg is NOT checked.  To say that another
1309 # way, be sure NOT to pass an editor argument if you want your token checked.
1310 # Otherwise the auth arg is just a flag saying "check the editor".  
1311
1312 sub ou_ancestor_setting {
1313     my( $self, $orgid, $name, $e, $auth ) = @_;
1314     $e = $e || OpenILS::Utils::CStoreEditor->new(
1315         (defined $auth) ? (authtoken => $auth) : ()
1316     );
1317
1318     if ($auth) {
1319         my $coust = $e->retrieve_config_org_unit_setting_type([
1320             $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1321         ]);
1322         if ($coust && $coust->view_perm) {
1323             # And you can't have permission if you don't have a valid session.
1324             return undef if not $e->checkauth;
1325             # And now that we know you MIGHT have permission, we check it.
1326             return undef if not $e->allowed($coust->view_perm->code, $orgid);
1327         }
1328     }
1329
1330     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1331     my $setting = $e->json_query($query)->[0];
1332     return undef unless $setting;
1333     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1334 }   
1335
1336 # This fetches a set of OU settings in one fell swoop,
1337 # which can be significantly faster than invoking
1338 # $U->ou_ancestor_setting() one setting at a time.
1339 # As the "_insecure" implies, however, callers are
1340 # responsible for ensuring that the settings to be
1341 # fetch do not need view permission checks.
1342 sub ou_ancestor_setting_batch_insecure {
1343     my( $self, $orgid, $names ) = @_;
1344
1345     my %result = map { $_ => undef } @$names;
1346     my $query = {
1347         from => [
1348             'actor.org_unit_ancestor_setting_batch',
1349             $orgid,
1350             '{' . join(',', @$names) . '}'
1351         ]
1352     };
1353     my $e = OpenILS::Utils::CStoreEditor->new();
1354     my $settings = $e->json_query($query);
1355     foreach my $setting (@$settings) {
1356         $result{$setting->{name}} = {
1357             org => $setting->{org_unit},
1358             value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})
1359         };
1360     }
1361     return %result;
1362 }
1363
1364 # Returns a hash of hashes like so:
1365 # { 
1366 #   $lookup_org_id => {org => $context_org, value => $setting_value},
1367 #   $lookup_org_id2 => {org => $context_org2, value => $setting_value2},
1368 #   $lookup_org_id3 => {} # example of no setting value exists
1369 #   ...
1370 # }
1371 sub ou_ancestor_setting_batch_by_org_insecure {
1372     my ($self, $org_ids, $name, $e) = @_;
1373
1374     $e ||= OpenILS::Utils::CStoreEditor->new();
1375     my %result = map { $_ => {value => undef} } @$org_ids;
1376
1377     my $query = {
1378         from => [
1379             'actor.org_unit_ancestor_setting_batch_by_org',
1380             $name, '{' . join(',', @$org_ids) . '}'
1381         ]
1382     };
1383
1384     # DB func returns an array of settings matching the order of the
1385     # list of org unit IDs.  If the setting does not contain a valid
1386     # ->id value, then no setting value exists for that org unit.
1387     my $settings = $e->json_query($query);
1388     for my $idx (0 .. $#$org_ids) {
1389         my $setting = $settings->[$idx];
1390         my $org_id = $org_ids->[$idx];
1391
1392         next unless $setting->{id}; # null ID means no value is present.
1393
1394         $result{$org_id}->{org} = $setting->{org_unit};
1395         $result{$org_id}->{value} = 
1396             OpenSRF::Utils::JSON->JSON2perl($setting->{value});
1397     }
1398
1399     return %result;
1400 }
1401
1402 # returns the ISO8601 string representation of the requested epoch in GMT
1403 sub epoch2ISO8601 {
1404     my( $self, $epoch ) = @_;
1405     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1406     $year += 1900; $mon += 1;
1407     my $date = sprintf(
1408         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1409         $year, $mon, $mday, $hour, $min, $sec);
1410     return $date;
1411 }
1412             
1413 sub find_highest_perm_org {
1414     my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1415     my $org = $self->find_org($org_tree, $start_org );
1416
1417     my $lastid = -1;
1418     while( $org ) {
1419         last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1420         $lastid = $org->id;
1421         $org = $self->find_org( $org_tree, $org->parent_ou() );
1422     }
1423
1424     return $lastid;
1425 }
1426
1427
1428 # returns the org_unit ID's 
1429 sub user_has_work_perm_at {
1430     my($self, $e, $perm, $options, $user_id) = @_;
1431     $options ||= {};
1432     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1433
1434     my $func = 'permission.usr_has_perm_at';
1435     $func = $func.'_all' if $$options{descendants};
1436
1437     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1438     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1439
1440     return $orgs unless $$options{objects};
1441
1442     return $e->search_actor_org_unit({id => $orgs});
1443 }
1444
1445 sub get_user_work_ou_ids {
1446     my($self, $e, $userid) = @_;
1447     my $work_orgs = $e->json_query({
1448         select => {puwoum => ['work_ou']},
1449         from => 'puwoum',
1450         where => {usr => $e->requestor->id}});
1451
1452     return [] unless @$work_orgs;
1453     my @work_orgs;
1454     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1455
1456     return \@work_orgs;
1457 }
1458
1459
1460 my $org_types;
1461 sub get_org_types {
1462     my($self, $client) = @_;
1463     return $org_types if $org_types;
1464     return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1465 }
1466
1467 my %ORG_TREE;
1468 sub get_org_tree {
1469     my $self = shift;
1470     my $locale = shift || '';
1471     my $cache = OpenSRF::Utils::Cache->new("global", 0);
1472     my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1473     $ORG_TREE{$locale} = $tree; # make sure to populate the process-local cache
1474     return $tree if $tree;
1475
1476     my $ses = OpenILS::Utils::CStoreEditor->new;
1477     $ses->session->session_locale($locale);
1478     $tree = $ses->search_actor_org_unit( 
1479         [
1480             {"parent_ou" => undef },
1481             {
1482                 flesh               => -1,
1483                 flesh_fields    => { aou =>  ['children'] },
1484                 order_by            => { aou => 'name'}
1485             }
1486         ]
1487     )->[0];
1488
1489     $ORG_TREE{$locale} = $tree;
1490     $cache->put_cache("orgtree.$locale", $tree);
1491     return $tree;
1492 }
1493
1494 sub get_global_flag {
1495     my($self, $flag) = @_;
1496     return undef unless ($flag);
1497     return OpenILS::Utils::CStoreEditor->new->retrieve_config_global_flag($flag);
1498 }
1499
1500 sub get_org_descendants {
1501     my($self, $org_id, $depth) = @_;
1502
1503     my $select = {
1504         transform => 'actor.org_unit_descendants',
1505         column => 'id',
1506         result_field => 'id',
1507     };
1508     $select->{params} = [$depth] if defined $depth;
1509
1510     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1511         select => {aou => [$select]},
1512         from => 'aou',
1513         where => {id => $org_id}
1514     });
1515     my @orgs;
1516     push(@orgs, $_->{id}) for @$org_list;
1517     return \@orgs;
1518 }
1519
1520 sub get_org_ancestors {
1521     my($self, $org_id, $use_cache) = @_;
1522
1523     my ($cache, $orgs);
1524
1525     if ($use_cache) {
1526         $cache = OpenSRF::Utils::Cache->new("global", 0);
1527         $orgs = $cache->get_cache("org.ancestors.$org_id");
1528         return $orgs if $orgs;
1529     }
1530
1531     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1532         select => {
1533             aou => [{
1534                 transform => 'actor.org_unit_ancestors',
1535                 column => 'id',
1536                 result_field => 'id',
1537                 params => []
1538             }],
1539         },
1540         from => 'aou',
1541         where => {id => $org_id}
1542     });
1543
1544     $orgs = [ map { $_->{id} } @$org_list ];
1545
1546     $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1547     return $orgs;
1548 }
1549
1550 sub get_org_full_path {
1551     my($self, $org_id, $depth) = @_;
1552
1553     my $query = {
1554         select => {
1555             aou => [{
1556                 transform => 'actor.org_unit_full_path',
1557                 column => 'id',
1558                 result_field => 'id',
1559             }],
1560         },
1561         from => 'aou',
1562         where => {id => $org_id}
1563     };
1564
1565     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1566     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1567     return [ map {$_->{id}} @$org_list ];
1568 }
1569
1570 # returns the ID of the org unit ancestor at the specified depth
1571 sub org_unit_ancestor_at_depth {
1572     my($class, $org_id, $depth) = @_;
1573     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1574         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1575     return ($resp) ? $resp->{id} : undef;
1576 }
1577
1578 # Returns the proximity value between two org units.
1579 sub get_org_unit_proximity {
1580     my ($class, $e, $from_org, $to_org) = @_;
1581     $e = OpenILS::Utils::CStoreEditor->new unless ($e);
1582     my $r = $e->json_query(
1583         {
1584             select => {aoup => ['prox']},
1585             from => 'aoup',
1586             where => {from_org => $from_org, to_org => $to_org}
1587         }
1588     );
1589     if (ref($r) eq 'ARRAY' && @$r) {
1590         return $r->[0]->{prox};
1591     }
1592     return undef;
1593 }
1594
1595 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1596 sub get_user_locale {
1597     my($self, $user_id, $e) = @_;
1598     $e ||= OpenILS::Utils::CStoreEditor->new;
1599
1600     # first, see if the user has an explicit locale set
1601     my $setting = $e->search_actor_user_setting(
1602         {usr => $user_id, name => 'global.locale'})->[0];
1603     return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1604
1605     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1606     return $self->get_org_locale($user->home_ou, $e);
1607 }
1608
1609 # returns org locale setting
1610 sub get_org_locale {
1611     my($self, $org_id, $e) = @_;
1612     $e ||= OpenILS::Utils::CStoreEditor->new;
1613
1614     my $locale;
1615     if(defined $org_id) {
1616         $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1617         return $locale if $locale;
1618     }
1619
1620     # system-wide default
1621     my $sclient = OpenSRF::Utils::SettingsClient->new;
1622     $locale = $sclient->config_value('default_locale');
1623     return $locale if $locale;
1624
1625     # if nothing else, fallback to locale=cowboy
1626     return 'en-US';
1627 }
1628
1629
1630 # xml-escape non-ascii characters
1631 sub entityize { 
1632     my($self, $string, $form) = @_;
1633     $form ||= "";
1634
1635     if ($form eq 'D') {
1636         $string = NFD($string);
1637     } else {
1638         $string = NFC($string);
1639     }
1640
1641     # Convert raw ampersands to entities
1642     $string =~ s/&(?!\S+;)/&amp;/gso;
1643
1644     # Convert Unicode characters to entities
1645     $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1646
1647     return $string;
1648 }
1649
1650 # x0000-x0008 isn't legal in XML documents
1651 # XXX Perhaps this should just go into our standard entityize method
1652 sub strip_ctrl_chars {
1653     my ($self, $string) = @_;
1654
1655     $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1656     return $string;
1657 }
1658
1659 sub get_copy_price {
1660     my($self, $e, $copy, $volume) = @_;
1661
1662     $copy->price(0) if $copy->price and $copy->price < 0;
1663
1664
1665     my $owner;
1666     if(ref $volume) {
1667         if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1668             $owner = $copy->circ_lib;
1669         } else {
1670             $owner = $volume->owning_lib;
1671         }
1672     } else {
1673         if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1674             $owner = $copy->circ_lib;
1675         } else {
1676             $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1677         }
1678     }
1679
1680     my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1681     my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1682     my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1683     my $primary_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_PRIMARY_ITEM_VALUE_FIELD, $e);
1684     my $backup_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_SECONDARY_ITEM_VALUE_FIELD, $e);
1685
1686     my $price = defined $primary_field && $primary_field eq 'cost'
1687         ? $copy->cost
1688         : $copy->price;
1689
1690     # set the default price if needed
1691     if (!defined $price or ($price == 0 and $charge_on_0)) {
1692         if (defined $backup_field && $backup_field eq 'cost') {
1693             $price = $copy->cost;
1694         } elsif (defined $backup_field && $backup_field eq 'price') {
1695             $price = $copy->price;
1696         }
1697     }
1698     # possible fallthrough to original default item price behavior
1699     if (!defined $price or ($price == 0 and $charge_on_0)) {
1700         # set to default price
1701         $price = $self->ou_ancestor_setting_value(
1702             $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1703     }
1704
1705     # adjust to min/max range if needed
1706     if (defined $max_price and $price > $max_price) {
1707         $price = $max_price;
1708     } elsif (defined $min_price and $price < $min_price
1709         and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1710         # default to raising the price to the minimum,
1711         # but let 0 fall through if $charge_on_0 is set and is false
1712         $price = $min_price;
1713     }
1714
1715     return $price;
1716 }
1717
1718 # given a transaction ID, this returns the context org_unit for the transaction
1719 sub xact_org {
1720     my($self, $xact_id, $e) = @_;
1721     $e ||= OpenILS::Utils::CStoreEditor->new;
1722     
1723     my $loc = $e->json_query({
1724         "select" => {circ => ["circ_lib"]},
1725         from     => "circ",
1726         "where"  => {id => $xact_id},
1727     });
1728
1729     return $loc->[0]->{circ_lib} if @$loc;
1730
1731     $loc = $e->json_query({
1732         "select" => {bresv => ["request_lib"]},
1733         from     => "bresv",
1734         "where"  => {id => $xact_id},
1735     });
1736
1737     return $loc->[0]->{request_lib} if @$loc;
1738
1739     $loc = $e->json_query({
1740         "select" => {mg => ["billing_location"]},
1741         from     => "mg",
1742         "where"  => {id => $xact_id},
1743     });
1744
1745     return $loc->[0]->{billing_location};
1746 }
1747
1748
1749 sub find_event_def_by_hook {
1750     my($self, $hook, $context_org, $e) = @_;
1751
1752     $e ||= OpenILS::Utils::CStoreEditor->new;
1753
1754     my $orgs = $self->get_org_ancestors($context_org);
1755
1756     # search from the context org up
1757     for my $org_id (reverse @$orgs) {
1758
1759         my $def = $e->search_action_trigger_event_definition(
1760             {hook => $hook, owner => $org_id, active => 't'})->[0];
1761
1762         return $def if $def;
1763     }
1764
1765     return undef;
1766 }
1767
1768
1769
1770 # If an event_def ID is not provided, use the hook and context org to find the 
1771 # most appropriate event.  create the event, fire it, then return the resulting
1772 # event with fleshed template_output and error_output
1773 sub fire_object_event {
1774     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1775
1776     my $e = OpenILS::Utils::CStoreEditor->new;
1777     my $def;
1778
1779     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1780
1781     if($event_def) {
1782         $def = $e->retrieve_action_trigger_event_definition($event_def)
1783             or return $e->event;
1784
1785         $auto_method .= '.include_inactive';
1786
1787     } else {
1788
1789         # find the most appropriate event def depending on context org
1790         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1791             or return $e->event;
1792     }
1793
1794     my $final_resp;
1795
1796     if($def->group_field) {
1797         # we have a list of objects
1798         $object = [$object] unless ref $object eq 'ARRAY';
1799
1800         my @event_ids;
1801         $user_data ||= [];
1802         for my $i (0..$#$object) {
1803             my $obj = $$object[$i];
1804             my $udata = $$user_data[$i];
1805             my $event_id = $self->simplereq(
1806                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1807             push(@event_ids, $event_id);
1808         }
1809
1810         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1811
1812         my $resp;
1813         if (not defined $client) {
1814             $resp = $self->simplereq(
1815                 'open-ils.trigger',
1816                 'open-ils.trigger.event_group.fire',
1817                 \@event_ids);
1818         } else {
1819             $resp = $self->patientreq(
1820                 $client,
1821                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1822                 \@event_ids
1823             );
1824         }
1825
1826         if($resp and $resp->{events} and @{$resp->{events}}) {
1827
1828             $e->xact_begin;
1829             $final_resp = $e->retrieve_action_trigger_event([
1830                 $resp->{events}->[0]->id,
1831                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1832             ]);
1833             $e->rollback;
1834         }
1835
1836     } else {
1837
1838         $object = $$object[0] if ref $object eq 'ARRAY';
1839
1840         my $event_id;
1841         my $resp;
1842
1843         if (not defined $client) {
1844             $event_id = $self->simplereq(
1845                 'open-ils.trigger',
1846                 $auto_method, $def->id, $object, $context_org, $user_data
1847             );
1848
1849             $resp = $self->simplereq(
1850                 'open-ils.trigger',
1851                 'open-ils.trigger.event.fire',
1852                 $event_id
1853             );
1854         } else {
1855             $event_id = $self->patientreq(
1856                 $client,
1857                 'open-ils.trigger',
1858                 $auto_method, $def->id, $object, $context_org, $user_data
1859             );
1860
1861             $resp = $self->patientreq(
1862                 $client,
1863                 'open-ils.trigger',
1864                 'open-ils.trigger.event.fire',
1865                 $event_id
1866             );
1867         }
1868         
1869         if($resp and $resp->{event}) {
1870             $e->xact_begin;
1871             $final_resp = $e->retrieve_action_trigger_event([
1872                 $resp->{event}->id,
1873                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1874             ]);
1875             $e->rollback;
1876         }
1877     }
1878
1879     return $final_resp;
1880 }
1881
1882
1883 sub create_events_for_hook {
1884     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1885     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1886     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1887         $hook, $obj, $org_id, $granularity, $user_data);
1888     return undef unless $wait;
1889     my $resp = $req->recv;
1890     return $resp->content if $resp;
1891 }
1892
1893 sub create_uuid_string {
1894     return create_UUID_as_string();
1895 }
1896
1897 sub create_circ_chain_summary {
1898     my($class, $e, $circ_id) = @_;
1899     my $sum = $e->json_query({from => ['action.summarize_all_circ_chain', $circ_id]})->[0];
1900     return undef unless $sum;
1901     my $obj = Fieldmapper::action::circ_chain_summary->new;
1902     $obj->$_($sum->{$_}) for keys %$sum;
1903     return $obj;
1904 }
1905
1906
1907 # Returns "mra" attribute key/value pairs for a set of bre's
1908 # Takes a list of bre IDs, returns a hash of hashes,
1909 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1910 my $ccvm_cache;
1911 sub get_bre_attrs {
1912     my ($class, $bre_ids, $e) = @_;
1913     $e = $e || OpenILS::Utils::CStoreEditor->new;
1914
1915     my $attrs = {};
1916     return $attrs unless defined $bre_ids;
1917     $bre_ids = [$bre_ids] unless ref $bre_ids;
1918
1919     my $mra = $e->json_query({
1920         select => {
1921             mra => [
1922                 {
1923                     column => 'id',
1924                     alias => 'bre'
1925                 }, {
1926                     column => 'attrs',
1927                     transform => 'each',
1928                     result_field => 'key',
1929                     alias => 'key'
1930                 },{
1931                     column => 'attrs',
1932                     transform => 'each',
1933                     result_field => 'value',
1934                     alias => 'value'
1935                 }
1936             ]
1937         },
1938         from => 'mra',
1939         where => {id => $bre_ids}
1940     });
1941
1942     return $attrs unless $mra;
1943
1944     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1945
1946     for my $id (@$bre_ids) {
1947         $attrs->{$id} = {};
1948         for my $mra (grep { $_->{bre} eq $id } @$mra) {
1949             my $ctype = $mra->{key};
1950             my $code = $mra->{value};
1951             $attrs->{$id}->{$ctype} = {code => $code};
1952             if($code) {
1953                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1954                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1955             }
1956         }
1957     }
1958
1959     return $attrs;
1960 }
1961
1962 # Shorter version of bib_container_items_via_search() below, only using
1963 # the queryparser record_list filter instead of the container filter.
1964 sub bib_record_list_via_search {
1965     my ($class, $search_query, $search_args) = @_;
1966
1967     # First, Use search API to get container items sorted in any way that crad
1968     # sorters support.
1969     my $search_result = $class->simplereq(
1970         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1971         $search_args, $search_query
1972     );
1973
1974     unless ($search_result) {
1975         # empty result sets won't cause this, but actual errors should.
1976         $logger->warn("bib_record_list_via_search() got nothing from search");
1977         return;
1978     }
1979
1980     # Throw away other junk from search, keeping only bib IDs.
1981     return [ map { shift @$_ } @{$search_result->{ids}} ];
1982 }
1983
1984 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1985 sub bib_container_items_via_search {
1986     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1987
1988     # First, Use search API to get container items sorted in any way that crad
1989     # sorters support.
1990     my $search_result = $class->simplereq(
1991         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1992         $search_args, $search_query
1993     );
1994     unless ($search_result) {
1995         # empty result sets won't cause this, but actual errors should.
1996         $logger->warn("bib_container_items_via_search() got nothing from search");
1997         return;
1998     }
1999
2000     # Throw away other junk from search, keeping only bib IDs.
2001     my $id_list = [ map { shift @$_ } @{$search_result->{ids}} ];
2002
2003     return [] unless @$id_list;
2004
2005     # Now get the bib container items themselves...
2006     my $e = new OpenILS::Utils::CStoreEditor;
2007     unless ($e) {
2008         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
2009         return;
2010     }
2011
2012     my @flesh_fields = qw/notes/;
2013     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
2014
2015     my $items = $e->search_container_biblio_record_entry_bucket_item([
2016         {
2017             "target_biblio_record_entry" => $id_list,
2018             "bucket" => $container_id
2019         }, {
2020             flesh => 1,
2021             flesh_fields => {"cbrebi" => \@flesh_fields}
2022         }
2023     ], {substream => 1});
2024
2025     unless ($items) {
2026         $logger->warn(
2027             "bib_container_items_via_search() couldn't get bucket items: " .
2028             $e->die_event->{textcode}
2029         );
2030         return;
2031     }
2032
2033     # ... and put them in the same order that the search API said they
2034     # should be in.
2035     my %ordering_hash = map { 
2036         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
2037         $_ 
2038     } @$items;
2039
2040     return [map { $ordering_hash{$_} } @$id_list];
2041 }
2042
2043 # returns undef on success, Event on error
2044 sub log_user_activity {
2045     my ($class, $user_id, $who, $what, $e, $async) = @_;
2046
2047     my $commit = 0;
2048     if (!$e) {
2049         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
2050         $commit = 1;
2051     }
2052
2053     my $res = $e->json_query({
2054         from => [
2055             'actor.insert_usr_activity', 
2056             $user_id, $who, $what, OpenSRF::AppSession->ingress
2057         ]
2058     });
2059
2060     if ($res) { # call returned OK
2061
2062         $e->commit   if $commit and @$res;
2063         $e->rollback if $commit and !@$res;
2064
2065     } else {
2066         return $e->die_event;
2067     }
2068
2069     return undef;
2070 }
2071
2072 # I hate to put this here exactly, but this code needs to be shared between
2073 # the TPAC's mod_perl module and open-ils.serial.
2074 #
2075 # There is a reason every part of the query *except* those parts dealing
2076 # with scope are moved here from the code's origin in TPAC.  The serials
2077 # use case does *not* want the same scoping logic.
2078 #
2079 # Also, note that for the serials uses case, we may filter in OPAC visible
2080 # status and copy/call_number deletedness, but we don't filter on any
2081 # particular values for serial.item.status or serial.item.date_received.
2082 # Since we're only using this *after* winnowing down the set of issuances
2083 # that copies should be related to, I'm not sure we need any such serial.item
2084 # filters.
2085
2086 sub basic_opac_copy_query {
2087     ######################################################################
2088     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2089     # not both.                                                          #
2090     ######################################################################
2091     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2092
2093     return {
2094         select => {
2095             acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
2096                     'age_protect', 'holdable', 'copy_number', 'circ_modifier'],
2097             acpl => [
2098                 {column => 'name', alias => 'copy_location'},
2099                 {column => 'holdable', alias => 'location_holdable'},
2100                 {column => 'url', alias => 'location_url'}
2101             ],
2102             ccs => [
2103                 {column => 'id', alias => 'status_code'},
2104                 {column => 'name', alias => 'copy_status'},
2105                 {column => 'holdable', alias => 'status_holdable'},
2106                 {column => 'is_available', alias => 'is_available'}
2107             ],
2108             acn => [
2109                 {column => 'label', alias => 'call_number_label'},
2110                 {column => 'id', alias => 'call_number'},
2111                 {column => 'owning_lib', alias => 'call_number_owning_lib'}
2112             ],
2113             circ => ['due_date',{column => 'circ_lib', alias => 'circ_circ_lib'}],
2114             acnp => [
2115                 {column => 'label', alias => 'call_number_prefix_label'},
2116                 {column => 'id', alias => 'call_number_prefix'}
2117             ],
2118             acns => [
2119                 {column => 'label', alias => 'call_number_suffix_label'},
2120                 {column => 'id', alias => 'call_number_suffix'}
2121             ],
2122             bmp => [
2123                 {column => 'label', alias => 'part_label'},
2124             ],
2125             ($staff ? (erfcc => ['circ_count']) : ()),
2126             crahp => [
2127                 {column => 'name', alias => 'age_protect_label'}
2128             ],
2129             ($iss_id ? (sitem => ["issuance"]) : ())
2130         },
2131
2132         from => {
2133             acp => [
2134                 {acn => { # 0
2135                     join => {
2136                         acnp => { fkey => 'prefix' },
2137                         acns => { fkey => 'suffix' }
2138                     },
2139                     filter => [
2140                         {deleted => 'f'},
2141                         ($rec_id ? {record => $rec_id} : ())
2142                     ],
2143                 }},
2144                 'aou', # 1
2145                 {circ => { # 2 If the copy is circulating, retrieve the open circ
2146                     type => 'left',
2147                     filter => {checkin_time => undef}
2148                 }},
2149                 {acpl => { # 3
2150                     filter => {
2151                         deleted => 'f',
2152                         ($staff ? () : ( opac_visible => 't' )),
2153                     },
2154                 }},
2155                 {ccs => { # 4
2156                     ($staff ? () : (filter => { opac_visible => 't' }))
2157                 }},
2158                 {acpm => { # 5
2159                     type => 'left',
2160                     join => {
2161                         bmp => { type => 'left', filter => { deleted => 'f' } }
2162                     }
2163                 }},
2164                 {'crahp' => { # 6
2165                     type => 'left'
2166                 }},
2167                 ($iss_id ? { # 7
2168                     sitem => {
2169                         fkey => 'id',
2170                         field => 'unit',
2171                         filter => {issuance => $iss_id},
2172                         join => {
2173                             sstr => { }
2174                         }
2175                     }
2176                 } : ()),
2177                 ($staff ? {
2178                     erfcc => {
2179                         fkey => 'id',
2180                         field => 'id'
2181                     }
2182                 }: ()),
2183             ]
2184         },
2185
2186         where => {
2187             '+acp' => {
2188                 deleted => 'f',
2189                 ($staff ? () : (opac_visible => 't'))
2190             },
2191             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2192             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2193         },
2194
2195         order_by => [
2196             {class => 'aou', field => 'name'},
2197             {class => 'acn', field => 'label_sortkey'},
2198             {class => 'acns', field => 'label_sortkey'},
2199             {class => 'bmp', field => 'label_sortkey'},
2200             {class => 'acp', field => 'copy_number'},
2201             {class => 'acp', field => 'barcode'}
2202         ],
2203
2204         limit => $copy_limit,
2205         offset => $copy_offset
2206     };
2207 }
2208
2209 # Compare two dates, date1 and date2. If date2 is not defined, then
2210 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2211 # supported by DateTime::Format::ISO8601. (A future enhancement might
2212 # be to support other formats.)
2213 #
2214 # Returns -1 if $date1 < $date2
2215 # Returns 0 if $date1 == $date2
2216 # Returns 1 if $date1 > $date2
2217 sub datecmp {
2218     my $self = shift;
2219     my $date1 = shift;
2220     my $date2 = shift;
2221
2222     # Check for timezone offsets and limit them to 2 digits:
2223     if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2224         $date1 = substr($date1, 0, length($date1) - 2);
2225     }
2226     if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2227         $date2 = substr($date2, 0, length($date2) - 2);
2228     }
2229
2230     # check date1:
2231     unless (UNIVERSAL::isa($date1, "DateTime")) {
2232         $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2233     }
2234
2235     # Check for date2:
2236     unless ($date2) {
2237         $date2 = DateTime->now;
2238     } else {
2239         unless (UNIVERSAL::isa($date2, "DateTime")) {
2240             $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2241         }
2242     }
2243
2244     return DateTime->compare($date1, $date2);
2245 }
2246
2247
2248 # marcdoc is an XML::LibXML document
2249 # updates the doc and returns the entityized MARC string
2250 sub strip_marc_fields {
2251     my ($class, $e, $marcdoc, $grps) = @_;
2252     
2253     my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2254
2255     my $query = {
2256         select  => {vibtf => ['field']},
2257         from    => {vibtf => 'vibtg'},
2258         where   => {'+vibtg' => {owner => $orgs}},
2259         distinct => 1
2260     };
2261
2262     # give me always-apply groups plus any selected groups
2263     if ($grps and @$grps) {
2264         $query->{where}->{'+vibtg'}->{'-or'} = [
2265             {id => $grps},
2266             {always_apply => 't'}
2267         ];
2268
2269     } else {
2270         $query->{where}->{'+vibtg'}->{always_apply} = 't';
2271     }
2272
2273     my $fields = $e->json_query($query);
2274
2275     for my $field (@$fields) {
2276         my $tag = $field->{field};
2277         for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2278             $node->parentNode->removeChild($node);
2279         }
2280     }
2281
2282     return $class->entityize($marcdoc->documentElement->toString);
2283 }
2284
2285 # marcdoc is an XML::LibXML document
2286 # updates the document and returns the entityized MARC string.
2287 sub set_marc_905u {
2288     my ($class, $marcdoc, $username) = @_;
2289
2290     # Look for existing 905$u subfields. If any exist, do nothing.
2291     my @nodes = $marcdoc->findnodes('//*[@tag="905"]/*[@code="u"]');
2292     unless (@nodes) {
2293         # We create a new 905 and the subfield u to that.
2294         my $parentNode = $marcdoc->createElement('datafield');
2295         $parentNode->setAttribute('tag', '905');
2296         $parentNode->setAttribute('ind1', '');
2297         $parentNode->setAttribute('ind2', '');
2298         $marcdoc->documentElement->addChild($parentNode);
2299         my $node = $marcdoc->createElement('subfield');
2300         $node->setAttribute('code', 'u');
2301         $node->appendTextNode($username);
2302         $parentNode->addChild($node);
2303
2304     }
2305
2306     return $class->entityize($marcdoc->documentElement->toString);
2307 }
2308
2309 # Given a list of PostgreSQL arrays of numbers,
2310 # unnest the numbers and return a unique set, skipping any list elements
2311 # that are just '{NULL}'.
2312 sub unique_unnested_numbers {
2313     my $class = shift;
2314
2315     no warnings 'numeric';
2316
2317     return undef unless ( scalar @_ );
2318
2319     return uniq(
2320         map(
2321             int,
2322             map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2323                 map { substr($_, 1, -1) } @_
2324         )
2325     );
2326 }
2327
2328 # Given a list of numbers, turn them into a PG array, skipping undef's
2329 sub intarray2pgarray {
2330     my $class = shift;
2331     no warnings 'numeric';
2332
2333     return '{' . join( ',', map(int, grep { defined && /^\d+$/ } @_) ) . '}';
2334 }
2335
2336 # Check if a transaction should be left open or closed. Close the
2337 # transaction if it should be closed or open it otherwise. Returns
2338 # undef on success or a failure event.
2339 sub check_open_xact {
2340     my( $self, $editor, $xactid, $xact ) = @_;
2341
2342     # Grab the transaction
2343     $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2344     return $editor->event unless $xact;
2345     $xactid ||= $xact->id;
2346
2347     # grab the summary and see how much is owed on this transaction
2348     my ($summary) = $self->fetch_mbts($xactid, $editor);
2349
2350     # grab the circulation if it is a circ;
2351     my $circ = $editor->retrieve_action_circulation($xactid);
2352
2353     # If nothing is owed on the transaction but it is still open
2354     # and this transaction is not an open circulation, close it
2355     if(
2356         ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2357         ( !$circ or $circ->stop_fines )) {
2358
2359         $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2360         $xact->xact_finish('now');
2361         $editor->update_money_billable_transaction($xact)
2362             or return $editor->event;
2363         return undef;
2364     }
2365
2366     # If money is owed or a refund is due on the xact and xact_finish
2367     # is set, clear it (to reopen the xact) and update
2368     if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2369         $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2370         $xact->clear_xact_finish;
2371         $editor->update_money_billable_transaction($xact)
2372             or return $editor->event;
2373         return undef;
2374     }
2375     return undef;
2376 }
2377
2378 # Because floating point math has rounding issues, and Dyrcona gets
2379 # tired of typing out the code to multiply floating point numbers
2380 # before adding and subtracting them and then dividing the result by
2381 # 100 each time, he wrote this little subroutine for subtracting
2382 # floating point values.  It can serve as a model for the other
2383 # operations if you like.
2384 #
2385 # It takes a list of floating point values as arguments.  The rest are
2386 # all subtracted from the first and the result is returned.  The
2387 # values are all multiplied by 100 before being used, and the result
2388 # is divided by 100 in order to avoid decimal rounding errors inherent
2389 # in floating point math.
2390 #
2391 # XXX shifting using multiplication/division *may* still introduce
2392 # rounding errors -- better to implement using string manipulation?
2393 sub fpdiff {
2394     my ($class, @args) = @_;
2395     my $result = shift(@args) * 100;
2396     while (my $arg = shift(@args)) {
2397         $result -= $arg * 100;
2398     }
2399     return $result / 100;
2400 }
2401
2402 sub fpsum {
2403     my ($class, @args) = @_;
2404     my $result = shift(@args) * 100;
2405     while (my $arg = shift(@args)) {
2406         $result += $arg * 100;
2407     }
2408     return $result / 100;
2409 }
2410
2411 # Non-migrated passwords can be verified directly in the DB
2412 # with any extra hashing.
2413 sub verify_user_password {
2414     my ($class, $e, $user_id, $passwd, $pw_type) = @_;
2415
2416     $pw_type ||= 'main'; # primary login password
2417
2418     my $verify = $e->json_query({
2419         from => [
2420             'actor.verify_passwd', 
2421             $user_id, $pw_type, $passwd
2422         ]
2423     })->[0];
2424
2425     return $class->is_true($verify->{'actor.verify_passwd'});
2426 }
2427
2428 # Passwords migrated from the original MD5 scheme are passed through 2
2429 # extra layers of MD5 hashing for backwards compatibility with the
2430 # MD5 passwords of yore and the MD5-based chap-style authentication.  
2431 # Passwords are stored in the DB like this:
2432 # CRYPT( MD5( pw_salt || MD5(real_password) ), pw_salt )
2433 #
2434 # If 'as_md5' is true, the password provided has already been
2435 # MD5 hashed.
2436 sub verify_migrated_user_password {
2437     my ($class, $e, $user_id, $passwd, $as_md5) = @_;
2438
2439     # 'main' is the primary login password. This is the only password 
2440     # type that requires the additional MD5 hashing.
2441     my $pw_type = 'main';
2442
2443     # Sometimes we have the bare password, sometimes the MD5 version.
2444     my $md5_pass = $as_md5 ? $passwd : md5_hex($passwd);
2445
2446     my $salt = $e->json_query({
2447         from => [
2448             'actor.get_salt', 
2449             $user_id, 
2450             $pw_type
2451         ]
2452     })->[0];
2453
2454     $salt = $salt->{'actor.get_salt'};
2455
2456     return $class->verify_user_password(
2457         $e, $user_id, md5_hex($salt . $md5_pass), $pw_type);
2458 }
2459
2460
2461 # generate a MARC XML document from a MARC XML string
2462 sub marc_xml_to_doc {
2463     my ($class, $xml) = @_;
2464     my $marc_doc = XML::LibXML->new->parse_string($xml);
2465     $marc_doc->documentElement->setNamespace($MARC_NAMESPACE, 'marc', 1);
2466     $marc_doc->documentElement->setNamespace($MARC_NAMESPACE);
2467     return $marc_doc;
2468 }
2469
2470
2471
2472 1;
2473