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