]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
Merge branch 'master' of git+ssh://yeti.esilibrary.com/home/evergreen/evergreen-equin...
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Account.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 my $U = 'OpenILS::Application::AppUtils';
9
10
11 # context additions: 
12 #   user : au object, fleshed
13 sub load_myopac {
14     my $self = shift;
15     $self->ctx->{page} = 'myopac';
16
17     $self->ctx->{user} = $self->editor->retrieve_actor_user([
18         $self->ctx->{user}->id,
19         {
20             flesh => 1,
21             flesh_fields => {
22                 au => ['card']
23                 # ...
24             }
25         }
26     ]);
27
28     return Apache2::Const::OK;
29 }
30
31
32 sub fetch_user_holds {
33     my $self = shift;
34     my $hold_ids = shift;
35     my $ids_only = shift;
36     my $flesh = shift;
37     my $available = shift;
38     my $limit = shift;
39     my $offset = shift;
40
41     my $e = $self->editor;
42
43     my $circ = OpenSRF::AppSession->create('open-ils.circ');
44
45     if(!$hold_ids) {
46
47         $hold_ids = $circ->request(
48             'open-ils.circ.holds.id_list.retrieve.authoritative', 
49             $e->authtoken, 
50             $e->requestor->id
51         )->gather(1);
52     
53         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
54     }
55
56
57     return $hold_ids if $ids_only or @$hold_ids == 0;
58
59     my $args = {
60         suppress_notices => 1,
61         suppress_transits => 1,
62         suppress_mvr => 1,
63         suppress_patron_details => 1,
64         include_bre => $flesh ? 1 : 0
65     };
66
67     # ----------------------------------------------------------------
68     # Collect holds in batches of $batch_size for faster retrieval
69
70     my $batch_size = 8;
71     my $batch_idx = 0;
72     my $mk_req_batch = sub {
73         my @ses;
74         my $top_idx = $batch_idx + $batch_size;
75         while($batch_idx < $top_idx) {
76             my $hold_id = $hold_ids->[$batch_idx++];
77             last unless $hold_id;
78             my $ses = OpenSRF::AppSession->create('open-ils.circ');
79             my $req = $ses->request(
80                 'open-ils.circ.hold.details.retrieve', 
81                 $e->authtoken, $hold_id, $args);
82             push(@ses, {ses => $ses, req => $req});
83         }
84         return @ses;
85     };
86
87     my $first = 1;
88     my(@collected, @holds, @ses);
89
90     while(1) {
91         @ses = $mk_req_batch->() if $first;
92         last if $first and not @ses;
93
94         if(@collected) {
95             # If desired by the caller, filter any holds that are not available.
96             if ($available) {
97                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
98             }
99             while(my $blob = pop(@collected)) {
100                 $blob->{marc_xml} = XML::LibXML->new->parse_string($blob->{hold}->{bre}->marc) if $flesh;
101                 push(@holds, $blob);
102             }
103         }
104
105         for my $req_data (@ses) {
106             push(@collected, {hold => $req_data->{req}->gather(1)});
107             $req_data->{ses}->kill_me;
108         }
109
110         @ses = $mk_req_batch->();
111         last unless @collected or @ses;
112         $first = 0;
113     }
114
115     # put the holds back into the original server sort order
116     my @sorted;
117     for my $id (@$hold_ids) {
118         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
119     }
120
121     return \@sorted;
122 }
123
124 sub handle_hold_update {
125     my $self = shift;
126     my $action = shift;
127     my $e = $self->editor;
128
129
130     my @hold_ids = $self->cgi->param('hold_id'); # for non-_all actions
131     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
132
133     my $circ = OpenSRF::AppSession->create('open-ils.circ');
134
135     if($action =~ /cancel/) {
136
137         for my $hold_id (@hold_ids) {
138             my $resp = $circ->request(
139                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
140         }
141
142     } else {
143         
144         my $vlist = [];
145         for my $hold_id (@hold_ids) {
146             my $vals = {id => $hold_id};
147
148             if($action =~ /activate/) {
149                 $vals->{frozen} = 'f';
150                 $vals->{thaw_date} = undef;
151
152             } elsif($action =~ /suspend/) {
153                 $vals->{frozen} = 't';
154                 # $vals->{thaw_date} = TODO;
155             }
156             push(@$vlist, $vals);
157         }
158
159         $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
160     }
161
162     $circ->kill_me;
163     return undef;
164 }
165
166 sub load_myopac_holds {
167     my $self = shift;
168     my $e = $self->editor;
169     my $ctx = $self->ctx;
170     
171
172     my $limit = $self->cgi->param('limit') || 0;
173     my $offset = $self->cgi->param('offset') || 0;
174     my $action = $self->cgi->param('action') || '';
175     my $available = int($self->cgi->param('available') || 0);
176
177     $self->handle_hold_update($action) if $action;
178
179     $ctx->{holds} = $self->fetch_user_holds(undef, 0, 1, $available, $limit, $offset);
180
181     return Apache2::Const::OK;
182 }
183
184 sub load_place_hold {
185     my $self = shift;
186     my $ctx = $self->ctx;
187     my $e = $self->editor;
188     my $cgi = $self->cgi;
189     $self->ctx->{page} = 'place_hold';
190
191     $ctx->{hold_target} = $cgi->param('hold_target');
192     $ctx->{hold_type} = $cgi->param('hold_type');
193     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # XXX staff
194
195     if($ctx->{hold_type} eq 'T') {
196         $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
197     }
198     # ...
199
200     $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
201
202     if(my $pickup_lib = $cgi->param('pickup_lib')) {
203
204         my $args = {
205             patronid => $e->requestor->id,
206             titleid => $ctx->{hold_target}, # XXX
207             pickup_lib => $pickup_lib,
208             depth => 0, # XXX
209         };
210
211         my $allowed = $U->simplereq(
212             'open-ils.circ',
213             'open-ils.circ.title_hold.is_possible',
214             $e->authtoken, $args
215         );
216
217         if($allowed->{success} == 1) {
218             my $hold = Fieldmapper::action::hold_request->new;
219
220             $hold->pickup_lib($pickup_lib);
221             $hold->requestor($e->requestor->id);
222             $hold->usr($e->requestor->id); # XXX staff
223             $hold->target($ctx->{hold_target});
224             $hold->hold_type($ctx->{hold_type});
225             # frozen, expired, etc..
226
227             my $stat = $U->simplereq(
228                 'open-ils.circ',
229                 'open-ils.circ.holds.create',
230                 $e->authtoken, $hold
231             );
232
233             if($stat and $stat > 0) {
234                 # if successful, return the user to the requesting page
235                 $self->apache->log->info("Redirecting back to " . $cgi->param('redirect_to'));
236                 $self->apache->print($cgi->redirect(-url => $cgi->param('redirect_to')));
237                 return Apache2::Const::REDIRECT;
238
239             } else {
240                 $ctx->{hold_failed} = 1;
241             }
242         } else { # hold *check* failed
243             $ctx->{hold_failed} = 1; # XXX process the events, etc
244             $ctx->{hold_failed_event} = $allowed->{last_event};
245         }
246
247         # hold permit failed
248         $logger->info('hold permit result ' . OpenSRF::Utils::JSON->perl2JSON($allowed));
249     }
250
251     return Apache2::Const::OK;
252 }
253
254
255 sub fetch_user_circs {
256     my $self = shift;
257     my $flesh = shift; # flesh bib data, etc.
258     my $circ_ids = shift;
259     my $limit = shift;
260     my $offset = shift;
261
262     my $e = $self->editor;
263
264     my @circ_ids;
265
266     if($circ_ids) {
267         @circ_ids = @$circ_ids;
268
269     } else {
270
271         my $circ_data = $U->simplereq(
272             'open-ils.actor', 
273             'open-ils.actor.user.checked_out',
274             $e->authtoken, 
275             $e->requestor->id
276         );
277
278         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
279
280         if($limit or $offset) {
281             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
282         }
283     }
284
285     return [] unless @circ_ids;
286
287     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
288
289     my $qflesh = {
290         flesh => 3,
291         flesh_fields => {
292             circ => ['target_copy'],
293             acp => ['call_number'],
294             acn => ['record']
295         }
296     };
297
298     $e->xact_begin;
299     my $circs = $e->search_action_circulation(
300         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
301
302     my @circs;
303     for my $circ (@$circs) {
304         push(@circs, {
305             circ => $circ, 
306             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
307                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
308                 undef  # pre-cat copy, use the dummy title/author instead
309         });
310     }
311     $e->xact_rollback;
312
313     # make sure the final list is in the correct order
314     my @sorted_circs;
315     for my $id (@circ_ids) {
316         push(
317             @sorted_circs,
318             (grep { $_->{circ}->id == $id } @circs)
319         );
320     }
321
322     return \@sorted_circs;
323 }
324
325
326 sub handle_circ_renew {
327     my $self = shift;
328     my $action = shift;
329     my $ctx = $self->ctx;
330
331     my @renew_ids = $self->cgi->param('circ');
332
333     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
334
335     # TODO: fire off renewal calls in batches to speed things up
336     my @responses;
337     for my $circ (@$circs) {
338
339         my $evt = $U->simplereq(
340             'open-ils.circ', 
341             'open-ils.circ.renew',
342             $self->editor->authtoken,
343             {
344                 patron_id => $self->editor->requestor->id,
345                 copy_id => $circ->{circ}->target_copy,
346                 opac_renewal => 1
347             }
348         );
349
350         # TODO return these, then insert them into the circ data 
351         # blob that is shoved into the template for each circ
352         # so the template won't have to match them
353         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
354     }
355
356     return @responses;
357 }
358
359
360 sub load_myopac_circs {
361     my $self = shift;
362     my $e = $self->editor;
363     my $ctx = $self->ctx;
364
365     $ctx->{circs} = [];
366     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
367     my $offset = $self->cgi->param('offset') || 0;
368     my $action = $self->cgi->param('action') || '';
369
370     # perform the renewal first if necessary
371     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
372
373     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
374
375     my $success_renewals = 0;
376     my $failed_renewals = 0;
377     for my $data (@{$ctx->{circs}}) {
378         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
379
380         if($resp) {
381             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
382             $data->{renewal_response} = $evt;
383             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
384             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
385         }
386     }
387
388     $ctx->{success_renewals} = $success_renewals;
389     $ctx->{failed_renewals} = $failed_renewals;
390
391     return Apache2::Const::OK;
392 }
393
394 sub load_myopac_fines {
395     my $self = shift;
396     my $e = $self->editor;
397     my $ctx = $self->ctx;
398     $ctx->{"fines"} = {
399         "circulation" => [],
400         "grocery" => [],
401         "total_paid" => 0,
402         "total_owed" => 0,
403         "balance_owed" => 0
404     };
405
406     my $limit = $self->cgi->param('limit') || 0;
407     my $offset = $self->cgi->param('offset') || 0;
408
409     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
410
411     # TODO: This should really be a ML call, but the existing calls 
412     # return an excessive amount of data and don't offer streaming
413
414     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
415
416     my $req = $cstore->request(
417         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
418         {
419             usr => $e->requestor->id,
420             balance_owed => {'!=' => 0}
421         },
422         {
423             flesh => 4,
424             flesh_fields => {
425                 mobts => ['circulation', 'grocery'],
426                 mg => ['billings'],
427                 mb => ['btype'],
428                 circ => ['target_copy'],
429                 acp => ['call_number'],
430                 acn => ['record']
431             },
432             order_by => { mobts => 'xact_start' },
433             %paging
434         }
435     );
436
437     while(my $resp = $req->recv) {
438         my $mobts = $resp->content;
439         my $circ = $mobts->circulation;
440
441         my $last_billing;
442         if($mobts->grocery) {
443             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
444             $last_billing = pop(@billings);
445         }
446
447         # XXX TODO switch to some money-safe non-fp library for math
448         $ctx->{"fines"}->{$_} += $mobts->$_ for (
449             qw/total_paid total_owed balance_owed/
450         );
451
452         push(
453             @{$ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
454             {
455                 xact => $mobts,
456                 last_grocery_billing => $last_billing,
457                 marc_xml => ($mobts->xact_type ne 'circulation' or $circ->target_copy->call_number->id == -1) ?
458                     undef :
459                     XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc),
460             } 
461         );
462     }
463
464      return Apache2::Const::OK;
465 }       
466
467 sub load_myopac_update_email {
468     my $self = shift;
469     my $e = $self->editor;
470     my $ctx = $self->ctx;
471     my $email = $self->cgi->param('email') || '';
472
473     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
474         $ctx->{invalid_email} = $email;
475         return Apache2::Const::OK;
476     }
477
478     my $stat = $U->simplereq(
479         'open-ils.actor', 
480         'open-ils.actor.user.email.update', 
481         $e->authtoken, $email);
482
483     my $url = $self->apache->unparsed_uri;
484     $url =~ s/update_email/main/;
485     $self->apache->print($self->cgi->redirect(-url => $url));
486
487     return Apache2::Const::REDIRECT;
488 }
489
490 sub load_myopac_bookbags {
491     my $self = shift;
492     my $e = $self->editor;
493     my $ctx = $self->ctx;
494     my $limit = $self->cgi->param('limit') || 0;
495     my $offset = $self->cgi->param('offset') || 0;
496
497     my $args = {order_by => {cbreb => 'name'}};
498     $args->{limit} = $limit if $limit;
499     $args->{offset} = $limit if $limit;
500
501     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket([
502         {owner => $self->editor->requestor->id, btype => 'bookbag'},
503         $args
504     ]);
505
506     return Apache2::Const::OK;
507 }
508
509
510 1