]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Utils/Editor.pm
added a retrieve_all wrapper
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Utils / Editor.pm
1 use strict; use warnings;
2 package OpenILS::Utils::Editor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::AppSession;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Event;
8 use Data::Dumper;
9 use OpenSRF::Utils::Logger qw($logger);
10 my $U = "OpenILS::Application::AppUtils";
11
12
13 # -----------------------------------------------------------------------------
14 # Export some useful functions
15 # -----------------------------------------------------------------------------
16 use vars qw(@EXPORT_OK %EXPORT_TAGS);
17 use Exporter;
18 use base qw/Exporter/;
19 push @EXPORT_OK, 'new_editor';
20 %EXPORT_TAGS = ( funcs => [ qw/ new_editor / ] );
21
22 sub new_editor { return OpenILS::Utils::Editor->new(@_); }
23
24
25 # -----------------------------------------------------------------------------
26 # These need to be auto-generated
27 # -----------------------------------------------------------------------------
28 my %PERMS = (
29         'biblio.record_entry'   => { update => 'UPDATE_MARC' },
30         'asset.copy'                            => { update => 'UPDATE_COPY'},
31         'asset.call_number'             => { update => 'UPDATE_VOLUME'},
32         'action.circulation'            => { retrieve => 'VIEW_CIRCULATIONS'},
33 );
34
35 my $logstr;
36 use constant E => 'error';
37 use constant W => 'warn';
38 use constant I => 'info';
39 use constant D => 'debug';
40 use constant A => 'activity';
41
42
43
44
45
46 # -----------------------------------------------------------------------------
47 # Params include:
48 #       xact=><true> : creates a storage transaction
49 #       authtoken=>$token : the login session key
50 # -----------------------------------------------------------------------------
51 sub new {
52         my( $class, %params ) = @_;
53         $class = ref($class) || $class;
54         my $self = bless( \%params, $class );
55         $self->{checked_perms} = {};
56         $logstr = "editor [0";
57         $logstr = "editor [1" if $self->{xact};
58         return $self;
59 }
60
61 # -----------------------------------------------------------------------------
62 # Log the editor metadata along with the log string
63 # -----------------------------------------------------------------------------
64 sub log {
65         my( $self, $lev, $str ) = @_;
66         my $s = "editor[";
67         $s .= "0|" unless $self->{xact};
68         $s .= "1|" if $self->{xact};
69         $s .= "0" unless $self->requestor;
70         $s .= $self->requestor->id if $self->requestor;
71         $s .= "]";
72         $logger->$lev("$s $str");
73 }
74
75 # -----------------------------------------------------------------------------
76 # Verifies the auth token and fetches the requestor object
77 # -----------------------------------------------------------------------------
78 sub checkauth {
79         my $self = shift;
80         $self->log(D, "checking auth token ".$self->authtoken);
81         my ($reqr, $evt) = $U->checkses($self->authtoken);
82         $self->event($evt) if $evt;
83         return $self->{requestor} = $reqr;
84 }
85
86
87 # -----------------------------------------------------------------------------
88 # Returns the last generated event
89 # -----------------------------------------------------------------------------
90 sub event {
91         my( $self, $evt ) = @_;
92         $self->{event} = $evt if $evt;
93         return $self->{event};
94 }
95
96 # -----------------------------------------------------------------------------
97 # Clears the last caught event
98 # -----------------------------------------------------------------------------
99 sub clear_event {
100         my $self = shift;
101         $self->{event} = undef;
102 }
103
104 sub authtoken {
105         my( $self, $auth ) = @_;
106         $self->{authtoken} = $auth if $auth;
107         return $self->{authtoken};
108 }
109
110 # -----------------------------------------------------------------------------
111 # fetches the session, creating if necessary.  If 'xact' is true on this
112 # object, a db session is created
113 # -----------------------------------------------------------------------------
114 sub session {
115         my( $self, $session ) = @_;
116         $self->{session} = $session if $session;
117
118         if(!$self->{session}) {
119                 $self->{session} = OpenSRF::AppSession->create('open-ils.storage');
120
121                 if( ! $self->{session} ) {
122                         my $str = "Error creating storage session with OpenSRF::AppSession->create()!";
123                         $self->log(E, $str);
124                         throw OpenSRF::EX::ERROR ($str);
125                 }
126
127                 $self->{session}->connect if $self->{xact} or $self->{connect};
128                 $self->xact_start if $self->{xact};
129         }
130         return $self->{session};
131 }
132
133
134 # -----------------------------------------------------------------------------
135 # Starts a storage transaction
136 # -----------------------------------------------------------------------------
137 sub xact_start {
138         my $self = shift;
139         $self->log(D, "starting new db session");
140         my $stat = $self->request('open-ils.storage.transaction.begin');
141         $self->log(E, "error starting database transaction") unless $stat;
142         return $stat;
143 }
144
145 # -----------------------------------------------------------------------------
146 # Commits a storage transaction
147 # -----------------------------------------------------------------------------
148 sub xact_commit {
149         my $self = shift;
150         $self->log(D, "comitting db session");
151         my $stat = $self->request('open-ils.storage.transaction.commit');
152         $self->log(E, "error comitting database transaction") unless $stat;
153         return $stat;
154 }
155
156 # -----------------------------------------------------------------------------
157 # Rolls back a storage stransaction
158 # -----------------------------------------------------------------------------
159 sub xact_rollback {
160         my $self = shift;
161         $self->log(I, "rolling back db session");
162         return $self->request("open-ils.storage.transaction.rollback");
163 }
164
165
166 # -----------------------------------------------------------------------------
167 # commits the db session and destroys the session
168 # -----------------------------------------------------------------------------
169 sub commit {
170         my $self = shift;
171         return unless $self->{xact};
172         $self->xact_commit;
173         $self->session->disconnect;
174         $self->{session} = undef;
175 }
176
177 # -----------------------------------------------------------------------------
178 # clears all object data. Does not commit the db transaction.
179 # -----------------------------------------------------------------------------
180 sub reset {
181         my $self = shift;
182         $self->session->disconnect if $self->{session};
183         $$self{$_} = undef for (keys %$self);
184 }
185
186
187 # -----------------------------------------------------------------------------
188 # commits and resets
189 # -----------------------------------------------------------------------------
190 sub finish {
191         my $self = shift;
192         $self->commit;
193         $self->reset;
194 }
195
196
197
198 # -----------------------------------------------------------------------------
199 # Does a simple storage request
200 # -----------------------------------------------------------------------------
201 sub request {
202         my( $self, $method, @params ) = @_;
203
204         my $val;
205         my $err;
206
207         try {
208                 $val = $self->session->request($method, @params)->gather(1);
209
210         } catch Error with {
211                 my $err = shift;
212                 $self->log(E, "request error $method=@params : $err");
213         };
214
215         throw $err if $err;
216         return $val;
217 }
218
219
220 # -----------------------------------------------------------------------------
221 # Sets / Returns the requstor object.  This is set when checkauth succeeds.
222 # -----------------------------------------------------------------------------
223 sub requestor {
224         my($self, $requestor) = @_;
225         $self->{requestor} = $requestor if $requestor;
226         return $self->{requestor};
227 }
228
229
230
231 # -----------------------------------------------------------------------------
232 # Holds the last data received from a storage call
233 # -----------------------------------------------------------------------------
234 sub data {
235         my( $self, $data ) = @_;
236         $self->{data} = $data if defined $data;
237         return $self->{data};
238 }
239
240
241 # -----------------------------------------------------------------------------
242 # True if this perm has already been checked at this org
243 # -----------------------------------------------------------------------------
244 sub perm_checked {
245         my( $self, $perm, $org ) = @_;
246         $self->{checked_perms}->{$org} = {}
247                 unless $self->{checked_perms}->{$org};
248         my $checked = $self->{checked_perms}->{$org}->{$perm};
249         if(!$checked) {
250                 $self->{checked_perms}->{$org}->{$perm} = 1;
251                 return 0;
252         }
253         return 1;
254 }
255
256
257
258 # -----------------------------------------------------------------------------
259 # Returns true if the requested perm is allowed.  If the perm check fails,
260 # $e->event is set and undef is returned
261 # The perm user is $e->requestor->id and perm org defaults to the requestor's
262 # ws_ou
263 # If this perm at the given org has already been verified, true is returned
264 # and the perm is not re-checked
265 # -----------------------------------------------------------------------------
266 sub allowed {
267         my( $self, $perm, $org ) = @_;
268         my $uid = $self->requestor->id;
269         $org ||= $self->requestor->ws_ou;
270         $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
271         return 1 if $self->perm_checked($perm, $org); 
272
273         my $s = $self->request(
274                 "open-ils.storage.permission.user_has_perm", $uid, $perm, $org );
275
276         if(!$s) {
277                 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
278                 $self->event($e);
279                 return undef;
280         }
281
282         return 1;
283 }
284
285
286
287 # -----------------------------------------------------------------------------
288 # checks the appropriate perm for the operation
289 # -----------------------------------------------------------------------------
290 sub checkperm {
291         my( $self, $ptype, $action, $org ) = @_;
292         $org ||= $self->requestor->ws_ou;
293         my $perm = $PERMS{$ptype}{$action};
294         if( $perm ) {
295                 return undef if $self->perm_checked($perm, $org);
296                 return $self->event unless $self->allowed($perm, $org);
297         } else {
298                 $self->log(E, "no perm provided for $ptype.$action");
299         }
300         return undef;
301 }
302
303
304
305 # -----------------------------------------------------------------------------
306 # Logs update actions to the activity log
307 # -----------------------------------------------------------------------------
308 sub log_activity {
309         my( $self, $type, $action, $arg ) = @_;
310         my $str = "$type.$action";
311         $str .= _prop_string($arg);
312         $self->log(A, $str);
313 }
314
315
316
317 sub _prop_string {
318         my $obj = shift;
319         my @props = $obj->properties;
320         my $str = "";
321         for(@props) {
322                 my $prop = $obj->$_() || "";
323                 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
324                 $str .= " $_=$prop";
325         }
326         return $str;
327 }
328
329 sub _hash_to_string {
330         my $h = shift;
331         my $str = "";
332         $str .= " $_=".$h->{$_} for keys %$h;
333         return $str;
334 }
335
336 sub _arg_to_string {
337         my( $action, $arg ) = @_;
338         return "" unless $arg;
339         return $arg->id if UNIVERSAL::isa($arg, "Fieldmapper");
340         return _hash_to_string($arg) if ref $arg eq 'HASH'; # search
341         return "[@$arg]" if ref $arg eq 'ARRAY';
342         return $arg; # retrieve
343 }
344
345
346
347 # -----------------------------------------------------------------------------
348 # This does the actual storage query.
349 #
350 # 'search' calls become search_where calls and $arg can be a search hash or
351 # an array-ref of storage search options.  
352 #
353 # 'retrieve' expects an id
354 # 'update' expects an object
355 # 'create' expects an object
356 # 'delete' expects an object
357 #
358 # All methods return true on success and undef on failure.  On failure, 
359 # $e->event is set to the generated event.  
360 # Note: this method assumes that updating a non-changed object and 
361 # thereby receiving a 0 from storage, is a successful update.  
362 #
363 # The method will therefore return true so the caller can just do 
364 # $e->update_blah($x) or return $e->event;
365 # The true value returned from storage for all methods will be stored in 
366 # $e->data, until the next method is called.
367 #
368 # not-found events are generated on retrieve and serach methods.
369 # action=search methods will return [] (==true) if no data is found.  If the
370 # caller is interested in the not found event, they can do:  
371 # return $e->event unless @$results; 
372 # -----------------------------------------------------------------------------
373 sub runmethod {
374         my( $self, $action, $type, $arg, $options ) = @_;
375
376         my @arg = ($arg);
377         my $method = "open-ils.storage.direct.$type.$action";
378         my $argstr = _arg_to_string($action, $arg);
379
380         if( $action eq 'search' ) {
381                 $method =~ s/search/search_where/o;
382                 $method =~ s/direct/id_list/o if $options->{idlist};
383                 $method = "$method.atomic";
384                 @arg = @$arg if ref($arg) eq 'ARRAY';
385
386         } elsif( $action eq 'batch_retrieve' ) {
387                 $method =~ s/batch_retrieve/batch.retrieve/o;
388                 $method = "$method.atomic";
389                 @arg = @$arg if ref($arg) eq 'ARRAY';
390
391         } elsif( $action eq 'retrieve_all' ) {
392                 $method =~ s/retrieve_all/retrieve.all.atomic/o;
393         }
394
395         # remove any stale events
396         $self->clear_event;
397
398         $self->log(I, "$type.$action : $argstr");
399         if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
400                 $self->log_activity($type, $action, $arg);
401         }
402
403         if($$options{checkperm}) {
404                 my $a = ($action eq 'search' or 
405                         $action eq 'batch_retrieve' or $action eq 'retrieve_all') ? 'retrieve' : $action;
406                 my $e = $self->checkperm($type, $a, $$options{permorg});
407                 if($e) {
408                         $self->event($e);
409                         return undef;
410                 }
411         }
412
413         my $obj; 
414         my $err;
415
416         try {
417                 $obj = $self->request($method, @arg);
418         } catch Error with { $err = shift; };
419         
420
421         if(!defined $obj) {
422                 $self->log(I, "request returned no data");
423
424                 if( $action eq 'retrieve' ) {
425                         $self->event(_mk_not_found($type, $arg));
426
427                 } elsif( $action eq 'update' or 
428                                 $action eq 'delete' or $action eq 'create' ) {
429                         my $evt = OpenILS::Event->new(
430                                 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
431                         $self->event($evt);
432                 }
433
434                 return undef;
435         }
436
437         if( $action eq 'create' and $obj == 0 ) {
438                 my $evt = OpenILS::Event->new(
439                         'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
440                 $self->event($evt);
441                 return undef;
442         }
443
444         if( $action eq 'search' or $action eq 'batch_retrieve' or $action eq 'retrieve_all') {
445                 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
446                 $self->event(_mk_not_found($type, $arg)) unless @$obj;
447         }
448
449         $arg->id($obj) if $action eq 'create'; # grabs the id on create
450         $self->data($obj); # cache the data for convenience
451
452         return ($obj) ? $obj : 1;
453 }
454
455
456 sub _mk_not_found {
457         my( $type, $arg ) = @_;
458         (my $t = $type) =~ s/\./_/og;
459         $t = uc($t);
460         return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
461 }
462
463
464
465
466 # utility method for loading
467 sub __fm2meth { 
468         my $str = shift;
469         my $sep = shift;
470         $str =~ s/Fieldmapper:://o;
471         $str =~ s/::/$sep/g;
472         return $str;
473 }
474
475
476 # -------------------------------------------------------------
477 # Load up the methods from the FM classes
478 # -------------------------------------------------------------
479 my $map = $Fieldmapper::fieldmap;
480 for my $object (keys %$map) {
481         my $obj = __fm2meth($object,'_');
482         my $type = __fm2meth($object, '.');
483
484         my $update = "update_$obj";
485         my $updatef = 
486                 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
487         eval $updatef;
488
489         my $retrieve = "retrieve_$obj";
490         my $retrievef = 
491                 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
492         eval $retrievef;
493
494         my $search = "search_$obj";
495         my $searchf = 
496                 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
497         eval $searchf;
498
499         my $create = "create_$obj";
500         my $createf = 
501                 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
502         eval $createf;
503
504         my $delete = "delete_$obj";
505         my $deletef = 
506                 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
507         eval $deletef;
508
509         my $bretrieve = "batch_retrieve_$obj";
510         my $bretrievef = 
511                 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
512         eval $bretrievef;
513
514         my $retrieveall = "retrieve_all_$obj";
515         my $retrieveallf = 
516                 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";
517         eval $retrieveallf;
518
519
520 }
521
522
523
524 1;
525
526