]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AppUtils.pm
LP1930747: Add MARC_NAMESPACE to Const.pm
[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
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 proximity value between two org units.
1578 sub get_org_unit_proximity {
1579     my ($class, $e, $from_org, $to_org) = @_;
1580     $e = OpenILS::Utils::CStoreEditor->new unless ($e);
1581     my $r = $e->json_query(
1582         {
1583             select => {aoup => ['prox']},
1584             from => 'aoup',
1585             where => {from_org => $from_org, to_org => $to_org}
1586         }
1587     );
1588     if (ref($r) eq 'ARRAY' && @$r) {
1589         return $r->[0]->{prox};
1590     }
1591     return undef;
1592 }
1593
1594 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1595 sub get_user_locale {
1596     my($self, $user_id, $e) = @_;
1597     $e ||= OpenILS::Utils::CStoreEditor->new;
1598
1599     # first, see if the user has an explicit locale set
1600     my $setting = $e->search_actor_user_setting(
1601         {usr => $user_id, name => 'global.locale'})->[0];
1602     return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1603
1604     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1605     return $self->get_org_locale($user->home_ou, $e);
1606 }
1607
1608 # returns org locale setting
1609 sub get_org_locale {
1610     my($self, $org_id, $e) = @_;
1611     $e ||= OpenILS::Utils::CStoreEditor->new;
1612
1613     my $locale;
1614     if(defined $org_id) {
1615         $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1616         return $locale if $locale;
1617     }
1618
1619     # system-wide default
1620     my $sclient = OpenSRF::Utils::SettingsClient->new;
1621     $locale = $sclient->config_value('default_locale');
1622     return $locale if $locale;
1623
1624     # if nothing else, fallback to locale=cowboy
1625     return 'en-US';
1626 }
1627
1628
1629 # xml-escape non-ascii characters
1630 sub entityize { 
1631     my($self, $string, $form) = @_;
1632     $form ||= "";
1633
1634     if ($form eq 'D') {
1635         $string = NFD($string);
1636     } else {
1637         $string = NFC($string);
1638     }
1639
1640     # Convert raw ampersands to entities
1641     $string =~ s/&(?!\S+;)/&amp;/gso;
1642
1643     # Convert Unicode characters to entities
1644     $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1645
1646     return $string;
1647 }
1648
1649 # x0000-x0008 isn't legal in XML documents
1650 # XXX Perhaps this should just go into our standard entityize method
1651 sub strip_ctrl_chars {
1652     my ($self, $string) = @_;
1653
1654     $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1655     return $string;
1656 }
1657
1658 sub get_copy_price {
1659     my($self, $e, $copy, $volume) = @_;
1660
1661     $copy->price(0) if $copy->price and $copy->price < 0;
1662
1663
1664     my $owner;
1665     if(ref $volume) {
1666         if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1667             $owner = $copy->circ_lib;
1668         } else {
1669             $owner = $volume->owning_lib;
1670         }
1671     } else {
1672         if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1673             $owner = $copy->circ_lib;
1674         } else {
1675             $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1676         }
1677     }
1678
1679     my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1680     my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1681     my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1682
1683     my $price = $copy->price;
1684
1685     # set the default price if needed
1686     if (!defined $price or ($price == 0 and $charge_on_0)) {
1687         # set to default price
1688         $price = $self->ou_ancestor_setting_value(
1689             $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1690     }
1691
1692     # adjust to min/max range if needed
1693     if (defined $max_price and $price > $max_price) {
1694         $price = $max_price;
1695     } elsif (defined $min_price and $price < $min_price
1696         and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1697         # default to raising the price to the minimum,
1698         # but let 0 fall through if $charge_on_0 is set and is false
1699         $price = $min_price;
1700     }
1701
1702     return $price;
1703 }
1704
1705 # given a transaction ID, this returns the context org_unit for the transaction
1706 sub xact_org {
1707     my($self, $xact_id, $e) = @_;
1708     $e ||= OpenILS::Utils::CStoreEditor->new;
1709     
1710     my $loc = $e->json_query({
1711         "select" => {circ => ["circ_lib"]},
1712         from     => "circ",
1713         "where"  => {id => $xact_id},
1714     });
1715
1716     return $loc->[0]->{circ_lib} if @$loc;
1717
1718     $loc = $e->json_query({
1719         "select" => {bresv => ["request_lib"]},
1720         from     => "bresv",
1721         "where"  => {id => $xact_id},
1722     });
1723
1724     return $loc->[0]->{request_lib} if @$loc;
1725
1726     $loc = $e->json_query({
1727         "select" => {mg => ["billing_location"]},
1728         from     => "mg",
1729         "where"  => {id => $xact_id},
1730     });
1731
1732     return $loc->[0]->{billing_location};
1733 }
1734
1735
1736 sub find_event_def_by_hook {
1737     my($self, $hook, $context_org, $e) = @_;
1738
1739     $e ||= OpenILS::Utils::CStoreEditor->new;
1740
1741     my $orgs = $self->get_org_ancestors($context_org);
1742
1743     # search from the context org up
1744     for my $org_id (reverse @$orgs) {
1745
1746         my $def = $e->search_action_trigger_event_definition(
1747             {hook => $hook, owner => $org_id, active => 't'})->[0];
1748
1749         return $def if $def;
1750     }
1751
1752     return undef;
1753 }
1754
1755
1756
1757 # If an event_def ID is not provided, use the hook and context org to find the 
1758 # most appropriate event.  create the event, fire it, then return the resulting
1759 # event with fleshed template_output and error_output
1760 sub fire_object_event {
1761     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1762
1763     my $e = OpenILS::Utils::CStoreEditor->new;
1764     my $def;
1765
1766     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1767
1768     if($event_def) {
1769         $def = $e->retrieve_action_trigger_event_definition($event_def)
1770             or return $e->event;
1771
1772         $auto_method .= '.include_inactive';
1773
1774     } else {
1775
1776         # find the most appropriate event def depending on context org
1777         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1778             or return $e->event;
1779     }
1780
1781     my $final_resp;
1782
1783     if($def->group_field) {
1784         # we have a list of objects
1785         $object = [$object] unless ref $object eq 'ARRAY';
1786
1787         my @event_ids;
1788         $user_data ||= [];
1789         for my $i (0..$#$object) {
1790             my $obj = $$object[$i];
1791             my $udata = $$user_data[$i];
1792             my $event_id = $self->simplereq(
1793                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1794             push(@event_ids, $event_id);
1795         }
1796
1797         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1798
1799         my $resp;
1800         if (not defined $client) {
1801             $resp = $self->simplereq(
1802                 'open-ils.trigger',
1803                 'open-ils.trigger.event_group.fire',
1804                 \@event_ids);
1805         } else {
1806             $resp = $self->patientreq(
1807                 $client,
1808                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1809                 \@event_ids
1810             );
1811         }
1812
1813         if($resp and $resp->{events} and @{$resp->{events}}) {
1814
1815             $e->xact_begin;
1816             $final_resp = $e->retrieve_action_trigger_event([
1817                 $resp->{events}->[0]->id,
1818                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1819             ]);
1820             $e->rollback;
1821         }
1822
1823     } else {
1824
1825         $object = $$object[0] if ref $object eq 'ARRAY';
1826
1827         my $event_id;
1828         my $resp;
1829
1830         if (not defined $client) {
1831             $event_id = $self->simplereq(
1832                 'open-ils.trigger',
1833                 $auto_method, $def->id, $object, $context_org, $user_data
1834             );
1835
1836             $resp = $self->simplereq(
1837                 'open-ils.trigger',
1838                 'open-ils.trigger.event.fire',
1839                 $event_id
1840             );
1841         } else {
1842             $event_id = $self->patientreq(
1843                 $client,
1844                 'open-ils.trigger',
1845                 $auto_method, $def->id, $object, $context_org, $user_data
1846             );
1847
1848             $resp = $self->patientreq(
1849                 $client,
1850                 'open-ils.trigger',
1851                 'open-ils.trigger.event.fire',
1852                 $event_id
1853             );
1854         }
1855         
1856         if($resp and $resp->{event}) {
1857             $e->xact_begin;
1858             $final_resp = $e->retrieve_action_trigger_event([
1859                 $resp->{event}->id,
1860                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1861             ]);
1862             $e->rollback;
1863         }
1864     }
1865
1866     return $final_resp;
1867 }
1868
1869
1870 sub create_events_for_hook {
1871     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1872     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1873     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1874         $hook, $obj, $org_id, $granularity, $user_data);
1875     return undef unless $wait;
1876     my $resp = $req->recv;
1877     return $resp->content if $resp;
1878 }
1879
1880 sub create_uuid_string {
1881     return create_UUID_as_string();
1882 }
1883
1884 sub create_circ_chain_summary {
1885     my($class, $e, $circ_id) = @_;
1886     my $sum = $e->json_query({from => ['action.summarize_all_circ_chain', $circ_id]})->[0];
1887     return undef unless $sum;
1888     my $obj = Fieldmapper::action::circ_chain_summary->new;
1889     $obj->$_($sum->{$_}) for keys %$sum;
1890     return $obj;
1891 }
1892
1893
1894 # Returns "mra" attribute key/value pairs for a set of bre's
1895 # Takes a list of bre IDs, returns a hash of hashes,
1896 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1897 my $ccvm_cache;
1898 sub get_bre_attrs {
1899     my ($class, $bre_ids, $e) = @_;
1900     $e = $e || OpenILS::Utils::CStoreEditor->new;
1901
1902     my $attrs = {};
1903     return $attrs unless defined $bre_ids;
1904     $bre_ids = [$bre_ids] unless ref $bre_ids;
1905
1906     my $mra = $e->json_query({
1907         select => {
1908             mra => [
1909                 {
1910                     column => 'id',
1911                     alias => 'bre'
1912                 }, {
1913                     column => 'attrs',
1914                     transform => 'each',
1915                     result_field => 'key',
1916                     alias => 'key'
1917                 },{
1918                     column => 'attrs',
1919                     transform => 'each',
1920                     result_field => 'value',
1921                     alias => 'value'
1922                 }
1923             ]
1924         },
1925         from => 'mra',
1926         where => {id => $bre_ids}
1927     });
1928
1929     return $attrs unless $mra;
1930
1931     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1932
1933     for my $id (@$bre_ids) {
1934         $attrs->{$id} = {};
1935         for my $mra (grep { $_->{bre} eq $id } @$mra) {
1936             my $ctype = $mra->{key};
1937             my $code = $mra->{value};
1938             $attrs->{$id}->{$ctype} = {code => $code};
1939             if($code) {
1940                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1941                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1942             }
1943         }
1944     }
1945
1946     return $attrs;
1947 }
1948
1949 # Shorter version of bib_container_items_via_search() below, only using
1950 # the queryparser record_list filter instead of the container filter.
1951 sub bib_record_list_via_search {
1952     my ($class, $search_query, $search_args) = @_;
1953
1954     # First, Use search API to get container items sorted in any way that crad
1955     # sorters support.
1956     my $search_result = $class->simplereq(
1957         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1958         $search_args, $search_query
1959     );
1960
1961     unless ($search_result) {
1962         # empty result sets won't cause this, but actual errors should.
1963         $logger->warn("bib_record_list_via_search() got nothing from search");
1964         return;
1965     }
1966
1967     # Throw away other junk from search, keeping only bib IDs.
1968     return [ map { shift @$_ } @{$search_result->{ids}} ];
1969 }
1970
1971 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1972 sub bib_container_items_via_search {
1973     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1974
1975     # First, Use search API to get container items sorted in any way that crad
1976     # sorters support.
1977     my $search_result = $class->simplereq(
1978         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1979         $search_args, $search_query
1980     );
1981     unless ($search_result) {
1982         # empty result sets won't cause this, but actual errors should.
1983         $logger->warn("bib_container_items_via_search() got nothing from search");
1984         return;
1985     }
1986
1987     # Throw away other junk from search, keeping only bib IDs.
1988     my $id_list = [ map { shift @$_ } @{$search_result->{ids}} ];
1989
1990     return [] unless @$id_list;
1991
1992     # Now get the bib container items themselves...
1993     my $e = new OpenILS::Utils::CStoreEditor;
1994     unless ($e) {
1995         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1996         return;
1997     }
1998
1999     my @flesh_fields = qw/notes/;
2000     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
2001
2002     my $items = $e->search_container_biblio_record_entry_bucket_item([
2003         {
2004             "target_biblio_record_entry" => $id_list,
2005             "bucket" => $container_id
2006         }, {
2007             flesh => 1,
2008             flesh_fields => {"cbrebi" => \@flesh_fields}
2009         }
2010     ], {substream => 1});
2011
2012     unless ($items) {
2013         $logger->warn(
2014             "bib_container_items_via_search() couldn't get bucket items: " .
2015             $e->die_event->{textcode}
2016         );
2017         return;
2018     }
2019
2020     # ... and put them in the same order that the search API said they
2021     # should be in.
2022     my %ordering_hash = map { 
2023         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
2024         $_ 
2025     } @$items;
2026
2027     return [map { $ordering_hash{$_} } @$id_list];
2028 }
2029
2030 # returns undef on success, Event on error
2031 sub log_user_activity {
2032     my ($class, $user_id, $who, $what, $e, $async) = @_;
2033
2034     my $commit = 0;
2035     if (!$e) {
2036         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
2037         $commit = 1;
2038     }
2039
2040     my $res = $e->json_query({
2041         from => [
2042             'actor.insert_usr_activity', 
2043             $user_id, $who, $what, OpenSRF::AppSession->ingress
2044         ]
2045     });
2046
2047     if ($res) { # call returned OK
2048
2049         $e->commit   if $commit and @$res;
2050         $e->rollback if $commit and !@$res;
2051
2052     } else {
2053         return $e->die_event;
2054     }
2055
2056     return undef;
2057 }
2058
2059 # I hate to put this here exactly, but this code needs to be shared between
2060 # the TPAC's mod_perl module and open-ils.serial.
2061 #
2062 # There is a reason every part of the query *except* those parts dealing
2063 # with scope are moved here from the code's origin in TPAC.  The serials
2064 # use case does *not* want the same scoping logic.
2065 #
2066 # Also, note that for the serials uses case, we may filter in OPAC visible
2067 # status and copy/call_number deletedness, but we don't filter on any
2068 # particular values for serial.item.status or serial.item.date_received.
2069 # Since we're only using this *after* winnowing down the set of issuances
2070 # that copies should be related to, I'm not sure we need any such serial.item
2071 # filters.
2072
2073 sub basic_opac_copy_query {
2074     ######################################################################
2075     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2076     # not both.                                                          #
2077     ######################################################################
2078     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2079
2080     return {
2081         select => {
2082             acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
2083                     'age_protect', 'holdable', 'copy_number', 'circ_modifier'],
2084             acpl => [
2085                 {column => 'name', alias => 'copy_location'},
2086                 {column => 'holdable', alias => 'location_holdable'},
2087                 {column => 'url', alias => 'location_url'}
2088             ],
2089             ccs => [
2090                 {column => 'id', alias => 'status_code'},
2091                 {column => 'name', alias => 'copy_status'},
2092                 {column => 'holdable', alias => 'status_holdable'},
2093                 {column => 'is_available', alias => 'is_available'}
2094             ],
2095             acn => [
2096                 {column => 'label', alias => 'call_number_label'},
2097                 {column => 'id', alias => 'call_number'},
2098                 {column => 'owning_lib', alias => 'call_number_owning_lib'}
2099             ],
2100             circ => ['due_date',{column => 'circ_lib', alias => 'circ_circ_lib'}],
2101             acnp => [
2102                 {column => 'label', alias => 'call_number_prefix_label'},
2103                 {column => 'id', alias => 'call_number_prefix'}
2104             ],
2105             acns => [
2106                 {column => 'label', alias => 'call_number_suffix_label'},
2107                 {column => 'id', alias => 'call_number_suffix'}
2108             ],
2109             bmp => [
2110                 {column => 'label', alias => 'part_label'},
2111             ],
2112             crahp => [
2113                 {column => 'name', alias => 'age_protect_label'}
2114             ],
2115             ($iss_id ? (sitem => ["issuance"]) : ())
2116         },
2117
2118         from => {
2119             acp => [
2120                 {acn => { # 0
2121                     join => {
2122                         acnp => { fkey => 'prefix' },
2123                         acns => { fkey => 'suffix' }
2124                     },
2125                     filter => [
2126                         {deleted => 'f'},
2127                         ($rec_id ? {record => $rec_id} : ())
2128                     ],
2129                 }},
2130                 'aou', # 1
2131                 {circ => { # 2 If the copy is circulating, retrieve the open circ
2132                     type => 'left',
2133                     filter => {checkin_time => undef}
2134                 }},
2135                 {acpl => { # 3
2136                     filter => {
2137                         deleted => 'f',
2138                         ($staff ? () : ( opac_visible => 't' )),
2139                     },
2140                 }},
2141                 {ccs => { # 4
2142                     ($staff ? () : (filter => { opac_visible => 't' }))
2143                 }},
2144                 {acpm => { # 5
2145                     type => 'left',
2146                     join => {
2147                         bmp => { type => 'left', filter => { deleted => 'f' } }
2148                     }
2149                 }},
2150                 {'crahp' => { # 6
2151                     type => 'left'
2152                 }},
2153                 ($iss_id ? { # 7
2154                     sitem => {
2155                         fkey => 'id',
2156                         field => 'unit',
2157                         filter => {issuance => $iss_id},
2158                         join => {
2159                             sstr => { }
2160                         }
2161                     }
2162                 } : ())
2163             ]
2164         },
2165
2166         where => {
2167             '+acp' => {
2168                 deleted => 'f',
2169                 ($staff ? () : (opac_visible => 't'))
2170             },
2171             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2172             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2173         },
2174
2175         order_by => [
2176             {class => 'aou', field => 'name'},
2177             {class => 'acn', field => 'label_sortkey'},
2178             {class => 'acns', field => 'label_sortkey'},
2179             {class => 'bmp', field => 'label_sortkey'},
2180             {class => 'acp', field => 'copy_number'},
2181             {class => 'acp', field => 'barcode'}
2182         ],
2183
2184         limit => $copy_limit,
2185         offset => $copy_offset
2186     };
2187 }
2188
2189 # Compare two dates, date1 and date2. If date2 is not defined, then
2190 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2191 # supported by DateTime::Format::ISO8601. (A future enhancement might
2192 # be to support other formats.)
2193 #
2194 # Returns -1 if $date1 < $date2
2195 # Returns 0 if $date1 == $date2
2196 # Returns 1 if $date1 > $date2
2197 sub datecmp {
2198     my $self = shift;
2199     my $date1 = shift;
2200     my $date2 = shift;
2201
2202     # Check for timezone offsets and limit them to 2 digits:
2203     if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2204         $date1 = substr($date1, 0, length($date1) - 2);
2205     }
2206     if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2207         $date2 = substr($date2, 0, length($date2) - 2);
2208     }
2209
2210     # check date1:
2211     unless (UNIVERSAL::isa($date1, "DateTime")) {
2212         $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2213     }
2214
2215     # Check for date2:
2216     unless ($date2) {
2217         $date2 = DateTime->now;
2218     } else {
2219         unless (UNIVERSAL::isa($date2, "DateTime")) {
2220             $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2221         }
2222     }
2223
2224     return DateTime->compare($date1, $date2);
2225 }
2226
2227
2228 # marcdoc is an XML::LibXML document
2229 # updates the doc and returns the entityized MARC string
2230 sub strip_marc_fields {
2231     my ($class, $e, $marcdoc, $grps) = @_;
2232     
2233     my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2234
2235     my $query = {
2236         select  => {vibtf => ['field']},
2237         from    => {vibtf => 'vibtg'},
2238         where   => {'+vibtg' => {owner => $orgs}},
2239         distinct => 1
2240     };
2241
2242     # give me always-apply groups plus any selected groups
2243     if ($grps and @$grps) {
2244         $query->{where}->{'+vibtg'}->{'-or'} = [
2245             {id => $grps},
2246             {always_apply => 't'}
2247         ];
2248
2249     } else {
2250         $query->{where}->{'+vibtg'}->{always_apply} = 't';
2251     }
2252
2253     my $fields = $e->json_query($query);
2254
2255     for my $field (@$fields) {
2256         my $tag = $field->{field};
2257         for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2258             $node->parentNode->removeChild($node);
2259         }
2260     }
2261
2262     return $class->entityize($marcdoc->documentElement->toString);
2263 }
2264
2265 # marcdoc is an XML::LibXML document
2266 # updates the document and returns the entityized MARC string.
2267 sub set_marc_905u {
2268     my ($class, $marcdoc, $username) = @_;
2269
2270     # Look for existing 905$u subfields. If any exist, do nothing.
2271     my @nodes = $marcdoc->findnodes('//*[@tag="905"]/*[@code="u"]');
2272     unless (@nodes) {
2273         # We create a new 905 and the subfield u to that.
2274         my $parentNode = $marcdoc->createElement('datafield');
2275         $parentNode->setAttribute('tag', '905');
2276         $parentNode->setAttribute('ind1', '');
2277         $parentNode->setAttribute('ind2', '');
2278         $marcdoc->documentElement->addChild($parentNode);
2279         my $node = $marcdoc->createElement('subfield');
2280         $node->setAttribute('code', 'u');
2281         $node->appendTextNode($username);
2282         $parentNode->addChild($node);
2283
2284     }
2285
2286     return $class->entityize($marcdoc->documentElement->toString);
2287 }
2288
2289 # Given a list of PostgreSQL arrays of numbers,
2290 # unnest the numbers and return a unique set, skipping any list elements
2291 # that are just '{NULL}'.
2292 sub unique_unnested_numbers {
2293     my $class = shift;
2294
2295     no warnings 'numeric';
2296
2297     return undef unless ( scalar @_ );
2298
2299     return uniq(
2300         map(
2301             int,
2302             map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2303                 map { substr($_, 1, -1) } @_
2304         )
2305     );
2306 }
2307
2308 # Given a list of numbers, turn them into a PG array, skipping undef's
2309 sub intarray2pgarray {
2310     my $class = shift;
2311     no warnings 'numeric';
2312
2313     return '{' . join( ',', map(int, grep { defined && /^\d+$/ } @_) ) . '}';
2314 }
2315
2316 # Check if a transaction should be left open or closed. Close the
2317 # transaction if it should be closed or open it otherwise. Returns
2318 # undef on success or a failure event.
2319 sub check_open_xact {
2320     my( $self, $editor, $xactid, $xact ) = @_;
2321
2322     # Grab the transaction
2323     $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2324     return $editor->event unless $xact;
2325     $xactid ||= $xact->id;
2326
2327     # grab the summary and see how much is owed on this transaction
2328     my ($summary) = $self->fetch_mbts($xactid, $editor);
2329
2330     # grab the circulation if it is a circ;
2331     my $circ = $editor->retrieve_action_circulation($xactid);
2332
2333     # If nothing is owed on the transaction but it is still open
2334     # and this transaction is not an open circulation, close it
2335     if(
2336         ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2337         ( !$circ or $circ->stop_fines )) {
2338
2339         $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2340         $xact->xact_finish('now');
2341         $editor->update_money_billable_transaction($xact)
2342             or return $editor->event;
2343         return undef;
2344     }
2345
2346     # If money is owed or a refund is due on the xact and xact_finish
2347     # is set, clear it (to reopen the xact) and update
2348     if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2349         $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2350         $xact->clear_xact_finish;
2351         $editor->update_money_billable_transaction($xact)
2352             or return $editor->event;
2353         return undef;
2354     }
2355     return undef;
2356 }
2357
2358 # Because floating point math has rounding issues, and Dyrcona gets
2359 # tired of typing out the code to multiply floating point numbers
2360 # before adding and subtracting them and then dividing the result by
2361 # 100 each time, he wrote this little subroutine for subtracting
2362 # floating point values.  It can serve as a model for the other
2363 # operations if you like.
2364 #
2365 # It takes a list of floating point values as arguments.  The rest are
2366 # all subtracted from the first and the result is returned.  The
2367 # values are all multiplied by 100 before being used, and the result
2368 # is divided by 100 in order to avoid decimal rounding errors inherent
2369 # in floating point math.
2370 #
2371 # XXX shifting using multiplication/division *may* still introduce
2372 # rounding errors -- better to implement using string manipulation?
2373 sub fpdiff {
2374     my ($class, @args) = @_;
2375     my $result = shift(@args) * 100;
2376     while (my $arg = shift(@args)) {
2377         $result -= $arg * 100;
2378     }
2379     return $result / 100;
2380 }
2381
2382 sub fpsum {
2383     my ($class, @args) = @_;
2384     my $result = shift(@args) * 100;
2385     while (my $arg = shift(@args)) {
2386         $result += $arg * 100;
2387     }
2388     return $result / 100;
2389 }
2390
2391 # Non-migrated passwords can be verified directly in the DB
2392 # with any extra hashing.
2393 sub verify_user_password {
2394     my ($class, $e, $user_id, $passwd, $pw_type) = @_;
2395
2396     $pw_type ||= 'main'; # primary login password
2397
2398     my $verify = $e->json_query({
2399         from => [
2400             'actor.verify_passwd', 
2401             $user_id, $pw_type, $passwd
2402         ]
2403     })->[0];
2404
2405     return $class->is_true($verify->{'actor.verify_passwd'});
2406 }
2407
2408 # Passwords migrated from the original MD5 scheme are passed through 2
2409 # extra layers of MD5 hashing for backwards compatibility with the
2410 # MD5 passwords of yore and the MD5-based chap-style authentication.  
2411 # Passwords are stored in the DB like this:
2412 # CRYPT( MD5( pw_salt || MD5(real_password) ), pw_salt )
2413 #
2414 # If 'as_md5' is true, the password provided has already been
2415 # MD5 hashed.
2416 sub verify_migrated_user_password {
2417     my ($class, $e, $user_id, $passwd, $as_md5) = @_;
2418
2419     # 'main' is the primary login password. This is the only password 
2420     # type that requires the additional MD5 hashing.
2421     my $pw_type = 'main';
2422
2423     # Sometimes we have the bare password, sometimes the MD5 version.
2424     my $md5_pass = $as_md5 ? $passwd : md5_hex($passwd);
2425
2426     my $salt = $e->json_query({
2427         from => [
2428             'actor.get_salt', 
2429             $user_id, 
2430             $pw_type
2431         ]
2432     })->[0];
2433
2434     $salt = $salt->{'actor.get_salt'};
2435
2436     return $class->verify_user_password(
2437         $e, $user_id, md5_hex($salt . $md5_pass), $pw_type);
2438 }
2439
2440
2441 # generate a MARC XML document from a MARC XML string
2442 sub marc_xml_to_doc {
2443     my ($class, $xml) = @_;
2444     my $marc_doc = XML::LibXML->new->parse_string($xml);
2445     $marc_doc->documentElement->setNamespace(MARC_NAMESPACE, 'marc', 1);
2446     $marc_doc->documentElement->setNamespace(MARC_NAMESPACE);
2447     return $marc_doc;
2448 }
2449
2450
2451
2452 1;
2453