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