]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
added circulation history backend and template; use |-style regex containers to reduc...
[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 => [qw/card home_ou addresses ident_type/]
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                 return $self->generic_redirect;
237
238             } else {
239                 $ctx->{hold_failed} = 1;
240             }
241         } else { # hold *check* failed
242             $ctx->{hold_failed} = 1; # XXX process the events, etc
243             $ctx->{hold_failed_event} = $allowed->{last_event};
244         }
245
246         # hold permit failed
247         $logger->info('hold permit result ' . OpenSRF::Utils::JSON->perl2JSON($allowed));
248     }
249
250     return Apache2::Const::OK;
251 }
252
253
254 sub fetch_user_circs {
255     my $self = shift;
256     my $flesh = shift; # flesh bib data, etc.
257     my $circ_ids = shift;
258     my $limit = shift;
259     my $offset = shift;
260
261     my $e = $self->editor;
262
263     my @circ_ids;
264
265     if($circ_ids) {
266         @circ_ids = @$circ_ids;
267
268     } else {
269
270         my $circ_data = $U->simplereq(
271             'open-ils.actor', 
272             'open-ils.actor.user.checked_out',
273             $e->authtoken, 
274             $e->requestor->id
275         );
276
277         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
278
279         if($limit or $offset) {
280             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
281         }
282     }
283
284     return [] unless @circ_ids;
285
286     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
287
288     my $qflesh = {
289         flesh => 3,
290         flesh_fields => {
291             circ => ['target_copy'],
292             acp => ['call_number'],
293             acn => ['record']
294         }
295     };
296
297     $e->xact_begin;
298     my $circs = $e->search_action_circulation(
299         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
300
301     my @circs;
302     for my $circ (@$circs) {
303         push(@circs, {
304             circ => $circ, 
305             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
306                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
307                 undef  # pre-cat copy, use the dummy title/author instead
308         });
309     }
310     $e->xact_rollback;
311
312     # make sure the final list is in the correct order
313     my @sorted_circs;
314     for my $id (@circ_ids) {
315         push(
316             @sorted_circs,
317             (grep { $_->{circ}->id == $id } @circs)
318         );
319     }
320
321     return \@sorted_circs;
322 }
323
324
325 sub handle_circ_renew {
326     my $self = shift;
327     my $action = shift;
328     my $ctx = $self->ctx;
329
330     my @renew_ids = $self->cgi->param('circ');
331
332     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
333
334     # TODO: fire off renewal calls in batches to speed things up
335     my @responses;
336     for my $circ (@$circs) {
337
338         my $evt = $U->simplereq(
339             'open-ils.circ', 
340             'open-ils.circ.renew',
341             $self->editor->authtoken,
342             {
343                 patron_id => $self->editor->requestor->id,
344                 copy_id => $circ->{circ}->target_copy,
345                 opac_renewal => 1
346             }
347         );
348
349         # TODO return these, then insert them into the circ data 
350         # blob that is shoved into the template for each circ
351         # so the template won't have to match them
352         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
353     }
354
355     return @responses;
356 }
357
358
359 sub load_myopac_circs {
360     my $self = shift;
361     my $e = $self->editor;
362     my $ctx = $self->ctx;
363
364     $ctx->{circs} = [];
365     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
366     my $offset = $self->cgi->param('offset') || 0;
367     my $action = $self->cgi->param('action') || '';
368
369     # perform the renewal first if necessary
370     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
371
372     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
373
374     my $success_renewals = 0;
375     my $failed_renewals = 0;
376     for my $data (@{$ctx->{circs}}) {
377         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
378
379         if($resp) {
380             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
381             $data->{renewal_response} = $evt;
382             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
383             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
384         }
385     }
386
387     $ctx->{success_renewals} = $success_renewals;
388     $ctx->{failed_renewals} = $failed_renewals;
389
390     return Apache2::Const::OK;
391 }
392
393 sub load_myopac_circ_history {
394     my $self = shift;
395     my $e = $self->editor;
396     my $ctx = $self->ctx;
397     my $limit = $self->cgi->param('limit');
398     my $offset = $self->cgi->param('offset');
399
400     my $circs = $e->json_query({
401         from => ['action.usr_visible_circs', $e->requestor->id],
402         limit => $limit || 25,
403         offset => $offset || 0
404     });
405
406     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circs], $limit, $offset);
407
408     return Apache2::Const::OK;
409 }
410
411 sub load_myopac_hold_history {
412     my $self = shift;
413     my $e = $self->editor;
414     my $ctx = $self->ctx;
415     my $limit = $self->cgi->param('limit');
416     my $offset = $self->cgi->param('offset');
417
418     my $holds = $e->json_query({
419         from => ['action.usr_visible_holds', $e->requestor->id],
420         limit => $limit || 25,
421         offset => $offset || 0
422     });
423
424     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$holds], 0, 1, 0, $limit, $offset);
425
426     return Apache2::Const::OK;
427 }
428
429 sub load_myopac_fines {
430     my $self = shift;
431     my $e = $self->editor;
432     my $ctx = $self->ctx;
433     $ctx->{"fines"} = {
434         "circulation" => [],
435         "grocery" => [],
436         "total_paid" => 0,
437         "total_owed" => 0,
438         "balance_owed" => 0
439     };
440
441     my $limit = $self->cgi->param('limit') || 0;
442     my $offset = $self->cgi->param('offset') || 0;
443
444     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
445
446     # TODO: This should really be a ML call, but the existing calls 
447     # return an excessive amount of data and don't offer streaming
448
449     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
450
451     my $req = $cstore->request(
452         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
453         {
454             usr => $e->requestor->id,
455             balance_owed => {'!=' => 0}
456         },
457         {
458             flesh => 4,
459             flesh_fields => {
460                 mobts => ['circulation', 'grocery'],
461                 mg => ['billings'],
462                 mb => ['btype'],
463                 circ => ['target_copy'],
464                 acp => ['call_number'],
465                 acn => ['record']
466             },
467             order_by => { mobts => 'xact_start' },
468             %paging
469         }
470     );
471
472     while(my $resp = $req->recv) {
473         my $mobts = $resp->content;
474         my $circ = $mobts->circulation;
475
476         my $last_billing;
477         if($mobts->grocery) {
478             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
479             $last_billing = pop(@billings);
480         }
481
482         # XXX TODO switch to some money-safe non-fp library for math
483         $ctx->{"fines"}->{$_} += $mobts->$_ for (
484             qw/total_paid total_owed balance_owed/
485         );
486
487         push(
488             @{$ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
489             {
490                 xact => $mobts,
491                 last_grocery_billing => $last_billing,
492                 marc_xml => ($mobts->xact_type ne 'circulation' or $circ->target_copy->call_number->id == -1) ?
493                     undef :
494                     XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc),
495             } 
496         );
497     }
498
499      return Apache2::Const::OK;
500 }       
501
502 sub load_myopac_update_email {
503     my $self = shift;
504     my $e = $self->editor;
505     my $ctx = $self->ctx;
506     my $email = $self->cgi->param('email') || '';
507
508     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
509         $ctx->{invalid_email} = $email;
510         return Apache2::Const::OK;
511     }
512
513     my $stat = $U->simplereq(
514         'open-ils.actor', 
515         'open-ils.actor.user.email.update', 
516         $e->authtoken, $email);
517
518     my $url = $self->apache->unparsed_uri;
519     $url =~ s/update_email/prefs/;
520
521     return $self->generic_redirect($url);
522 }
523
524 sub load_myopac_bookbags {
525     my $self = shift;
526     my $e = $self->editor;
527     my $ctx = $self->ctx;
528
529     my $rv = $self->load_mylist;
530     return $rv if $rv ne Apache2::Const::OK;
531
532     my $args = {
533         order_by => {cbreb => 'name'},
534         limit => $self->cgi->param('limit') || 10,
535         offset => $self->cgi->param('limit') || 0
536     };
537
538     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket([
539         {owner => $self->editor->requestor->id, btype => 'bookbag'},
540         # XXX what to do about the possibility of really large bookbags here?
541         {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
542     ]) or return $e->die_event;
543
544     # get unique record IDs
545     my %rec_ids = ();
546     foreach my $bbag (@{$ctx->{bookbags}}) {
547         foreach my $rec_id (
548             map { $_->target_biblio_record_entry } @{$bbag->items}
549         ) {
550             $rec_ids{$rec_id} = 1;
551         }
552     }
553
554     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
555
556     return Apache2::Const::OK;
557 }
558
559
560 # actions are create, delete, show, hide, rename, add_rec, delete_item
561 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
562 sub load_myopac_bookbag_update {
563     my ($self, $action, $list_id) = @_;
564     my $e = $self->editor;
565     my $cgi = $self->cgi;
566
567     $action ||= $cgi->param('action');
568     $list_id ||= $cgi->param('list');
569
570     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
571     my @del_item = $cgi->param('del_item');
572     my $shared = $cgi->param('shared');
573     my $name = $cgi->param('name');
574     my $success = 0;
575     my $list;
576
577     if($action eq 'create') {
578         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
579         $list->name($name);
580         $list->owner($e->requestor->id);
581         $list->btype('bookbag');
582         $list->pub($shared ? 't' : 'f');
583         $success = $U->simplereq('open-ils.actor', 
584             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
585
586     } else {
587
588         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
589
590         return Apache2::Const::HTTP_BAD_REQUEST unless 
591             $list and $list->owner == $e->requestor->id;
592     }
593
594     if($action eq 'delete') {
595         $success = $U->simplereq('open-ils.actor', 
596             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
597
598     } elsif($action eq 'show') {
599         unless($U->is_true($list->pub)) {
600             $list->pub('t');
601             $success = $U->simplereq('open-ils.actor', 
602                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
603         }
604
605     } elsif($action eq 'hide') {
606         if($U->is_true($list->pub)) {
607             $list->pub('f');
608             $success = $U->simplereq('open-ils.actor', 
609                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
610         }
611
612     } elsif($action eq 'rename') {
613         if($name) {
614             $list->name($name);
615             $success = $U->simplereq('open-ils.actor', 
616                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
617         }
618
619     } elsif($action eq 'add_rec') {
620         foreach my $add_rec (@add_rec) {
621             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
622             $item->bucket($list_id);
623             $item->target_biblio_record_entry($add_rec);
624             $success = $U->simplereq('open-ils.actor', 
625                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
626             last unless $success;
627         }
628
629     } elsif($action eq 'del_item') {
630         foreach (@del_item) {
631             $success = $U->simplereq(
632                 'open-ils.actor',
633                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
634             );
635             last unless $success;
636         }
637     }
638
639     return $self->generic_redirect if $success;
640
641     $self->ctx->{bucket_action} = $action;
642     $self->ctx->{bucket_action_failed} = 1;
643     return Apache2::Const::OK;
644 }
645
646 1