fetch bookbags inside xact to avoid replication delays, which can occur directly...
[evergreen-equinox.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     my $url;
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     } elsif ($action =~ /activate|suspend/) {
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     } elsif ($action eq 'edit') {
161
162         my @vals = map {
163             my $val = {"id" => $_};
164             $val->{"frozen"} = $self->cgi->param("frozen");
165             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
166
167             for my $field (qw/expire_time thaw_date/) {
168                 # XXX TODO make this support other date formats, not just
169                 # MM/DD/YYYY.
170                 next unless $self->cgi->param($field) =~
171                     m:^(\d{2})/(\d{2})/(\d{4})$:;
172                 $val->{$field} = "$3-$1-$2";
173             }
174             $val;
175         } @hold_ids;
176
177         $circ->request(
178             'open-ils.circ.hold.update.batch.atomic',
179             $e->authtoken, undef, \@vals
180         )->gather(1);   # LFW XXX test for failure
181         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
182     }
183
184     $circ->kill_me;
185     return defined($url) ? $self->generic_redirect($url) : undef;
186 }
187
188 sub load_myopac_holds {
189     my $self = shift;
190     my $e = $self->editor;
191     my $ctx = $self->ctx;
192     
193
194     my $limit = $self->cgi->param('limit') || 0;
195     my $offset = $self->cgi->param('offset') || 0;
196     my $action = $self->cgi->param('action') || '';
197     my $available = int($self->cgi->param('available') || 0);
198
199     my $hold_handle_result;
200     $hold_handle_result = $self->handle_hold_update($action) if $action;
201
202     $ctx->{holds} = $self->fetch_user_holds(undef, 0, 1, $available, $limit, $offset);
203
204     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
205 }
206
207 sub load_place_hold {
208     my $self = shift;
209     my $ctx = $self->ctx;
210     my $e = $self->editor;
211     my $cgi = $self->cgi;
212     $self->ctx->{page} = 'place_hold';
213
214     $ctx->{hold_target} = $cgi->param('hold_target');
215     $ctx->{hold_type} = $cgi->param('hold_type');
216     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # XXX staff
217
218     if($ctx->{hold_type} eq 'T') {
219         $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
220     }
221     # ...
222
223     $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
224
225     if(my $pickup_lib = $cgi->param('pickup_lib')) {
226
227         my $args = {
228             patronid => $e->requestor->id,
229             titleid => $ctx->{hold_target}, # XXX
230             pickup_lib => $pickup_lib,
231             depth => 0, # XXX
232         };
233
234         my $allowed = $U->simplereq(
235             'open-ils.circ',
236             'open-ils.circ.title_hold.is_possible',
237             $e->authtoken, $args
238         );
239
240         if($allowed->{success} == 1) {
241             my $hold = Fieldmapper::action::hold_request->new;
242
243             $hold->pickup_lib($pickup_lib);
244             $hold->requestor($e->requestor->id);
245             $hold->usr($e->requestor->id); # XXX staff
246             $hold->target($ctx->{hold_target});
247             $hold->hold_type($ctx->{hold_type});
248             # frozen, expired, etc..
249
250             my $stat = $U->simplereq(
251                 'open-ils.circ',
252                 'open-ils.circ.holds.create',
253                 $e->authtoken, $hold
254             );
255
256             if($stat and $stat > 0) {
257                 # if successful, return the user to the requesting page
258                 $self->apache->log->info("Redirecting back to " . $cgi->param('redirect_to'));
259                 return $self->generic_redirect;
260
261             } else {
262                 $ctx->{hold_failed} = 1;
263             }
264         } else { # hold *check* failed
265             $ctx->{hold_failed} = 1; # XXX process the events, etc
266             $ctx->{hold_failed_event} = $allowed->{last_event};
267         }
268
269         # hold permit failed
270         $logger->info('hold permit result ' . OpenSRF::Utils::JSON->perl2JSON($allowed));
271     }
272
273     return Apache2::Const::OK;
274 }
275
276
277 sub fetch_user_circs {
278     my $self = shift;
279     my $flesh = shift; # flesh bib data, etc.
280     my $circ_ids = shift;
281     my $limit = shift;
282     my $offset = shift;
283
284     my $e = $self->editor;
285
286     my @circ_ids;
287
288     if($circ_ids) {
289         @circ_ids = @$circ_ids;
290
291     } else {
292
293         my $circ_data = $U->simplereq(
294             'open-ils.actor', 
295             'open-ils.actor.user.checked_out',
296             $e->authtoken, 
297             $e->requestor->id
298         );
299
300         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
301
302         if($limit or $offset) {
303             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
304         }
305     }
306
307     return [] unless @circ_ids;
308
309     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
310
311     my $qflesh = {
312         flesh => 3,
313         flesh_fields => {
314             circ => ['target_copy'],
315             acp => ['call_number'],
316             acn => ['record']
317         }
318     };
319
320     $e->xact_begin;
321     my $circs = $e->search_action_circulation(
322         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
323
324     my @circs;
325     for my $circ (@$circs) {
326         push(@circs, {
327             circ => $circ, 
328             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
329                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
330                 undef  # pre-cat copy, use the dummy title/author instead
331         });
332     }
333     $e->xact_rollback;
334
335     # make sure the final list is in the correct order
336     my @sorted_circs;
337     for my $id (@circ_ids) {
338         push(
339             @sorted_circs,
340             (grep { $_->{circ}->id == $id } @circs)
341         );
342     }
343
344     return \@sorted_circs;
345 }
346
347
348 sub handle_circ_renew {
349     my $self = shift;
350     my $action = shift;
351     my $ctx = $self->ctx;
352
353     my @renew_ids = $self->cgi->param('circ');
354
355     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
356
357     # TODO: fire off renewal calls in batches to speed things up
358     my @responses;
359     for my $circ (@$circs) {
360
361         my $evt = $U->simplereq(
362             'open-ils.circ', 
363             'open-ils.circ.renew',
364             $self->editor->authtoken,
365             {
366                 patron_id => $self->editor->requestor->id,
367                 copy_id => $circ->{circ}->target_copy,
368                 opac_renewal => 1
369             }
370         );
371
372         # TODO return these, then insert them into the circ data 
373         # blob that is shoved into the template for each circ
374         # so the template won't have to match them
375         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
376     }
377
378     return @responses;
379 }
380
381
382 sub load_myopac_circs {
383     my $self = shift;
384     my $e = $self->editor;
385     my $ctx = $self->ctx;
386
387     $ctx->{circs} = [];
388     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
389     my $offset = $self->cgi->param('offset') || 0;
390     my $action = $self->cgi->param('action') || '';
391
392     # perform the renewal first if necessary
393     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
394
395     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
396
397     my $success_renewals = 0;
398     my $failed_renewals = 0;
399     for my $data (@{$ctx->{circs}}) {
400         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
401
402         if($resp) {
403             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
404             $data->{renewal_response} = $evt;
405             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
406             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
407         }
408     }
409
410     $ctx->{success_renewals} = $success_renewals;
411     $ctx->{failed_renewals} = $failed_renewals;
412
413     return Apache2::Const::OK;
414 }
415
416 sub load_myopac_fines {
417     my $self = shift;
418     my $e = $self->editor;
419     my $ctx = $self->ctx;
420     $ctx->{"fines"} = {
421         "circulation" => [],
422         "grocery" => [],
423         "total_paid" => 0,
424         "total_owed" => 0,
425         "balance_owed" => 0
426     };
427
428     my $limit = $self->cgi->param('limit') || 0;
429     my $offset = $self->cgi->param('offset') || 0;
430
431     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
432
433     # TODO: This should really be a ML call, but the existing calls 
434     # return an excessive amount of data and don't offer streaming
435
436     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
437
438     my $req = $cstore->request(
439         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
440         {
441             usr => $e->requestor->id,
442             balance_owed => {'!=' => 0}
443         },
444         {
445             flesh => 4,
446             flesh_fields => {
447                 mobts => ['circulation', 'grocery'],
448                 mg => ['billings'],
449                 mb => ['btype'],
450                 circ => ['target_copy'],
451                 acp => ['call_number'],
452                 acn => ['record']
453             },
454             order_by => { mobts => 'xact_start' },
455             %paging
456         }
457     );
458
459     while(my $resp = $req->recv) {
460         my $mobts = $resp->content;
461         my $circ = $mobts->circulation;
462
463         my $last_billing;
464         if($mobts->grocery) {
465             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
466             $last_billing = pop(@billings);
467         }
468
469         # XXX TODO switch to some money-safe non-fp library for math
470         $ctx->{"fines"}->{$_} += $mobts->$_ for (
471             qw/total_paid total_owed balance_owed/
472         );
473
474         push(
475             @{$ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
476             {
477                 xact => $mobts,
478                 last_grocery_billing => $last_billing,
479                 marc_xml => ($mobts->xact_type ne 'circulation' or $circ->target_copy->call_number->id == -1) ?
480                     undef :
481                     XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc),
482             } 
483         );
484     }
485
486      return Apache2::Const::OK;
487 }       
488
489 sub load_myopac_update_email {
490     my $self = shift;
491     my $e = $self->editor;
492     my $ctx = $self->ctx;
493     my $email = $self->cgi->param('email') || '';
494
495     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
496         $ctx->{invalid_email} = $email;
497         return Apache2::Const::OK;
498     }
499
500     my $stat = $U->simplereq(
501         'open-ils.actor', 
502         'open-ils.actor.user.email.update', 
503         $e->authtoken, $email);
504
505     my $url = $self->apache->unparsed_uri;
506     $url =~ s/update_email/prefs/;
507
508     return $self->generic_redirect($url);
509 }
510
511 sub load_myopac_bookbags {
512     my $self = shift;
513     my $e = $self->editor;
514     my $ctx = $self->ctx;
515
516     $e->xact_begin; # replication...
517
518     my $rv = $self->load_mylist;
519     unless($rv eq Apache2::Const::OK) {
520         $e->rollback;
521         return $rv;
522     }
523
524     my $args = {
525         order_by => {cbreb => 'name'},
526         limit => $self->cgi->param('limit') || 10,
527         offset => $self->cgi->param('offset') || 0
528     };
529
530     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket([
531         {owner => $self->editor->requestor->id, btype => 'bookbag'},
532         # XXX what to do about the possibility of really large bookbags here?
533         {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
534     ]);
535
536     if(!$ctx->{bookbags}) {
537         $e->rollback;
538         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
539     }
540     
541     # get unique record IDs
542     my %rec_ids = ();
543     foreach my $bbag (@{$ctx->{bookbags}}) {
544         foreach my $rec_id (
545             map { $_->target_biblio_record_entry } @{$bbag->items}
546         ) {
547             $rec_ids{$rec_id} = 1;
548         }
549     }
550
551     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
552
553     $e->rollback;
554     return Apache2::Const::OK;
555 }
556
557
558 # actions are create, delete, show, hide, rename, add_rec, delete_item
559 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
560 sub load_myopac_bookbag_update {
561     my ($self, $action, $list_id) = @_;
562     my $e = $self->editor;
563     my $cgi = $self->cgi;
564
565     $action ||= $cgi->param('action');
566     $list_id ||= $cgi->param('list');
567
568     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
569     my @del_item = $cgi->param('del_item');
570     my $shared = $cgi->param('shared');
571     my $name = $cgi->param('name');
572     my $success = 0;
573     my $list;
574
575     if($action eq 'create') {
576         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
577         $list->name($name);
578         $list->owner($e->requestor->id);
579         $list->btype('bookbag');
580         $list->pub($shared ? 't' : 'f');
581         $success = $U->simplereq('open-ils.actor', 
582             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
583
584     } else {
585
586         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
587
588         return Apache2::Const::HTTP_BAD_REQUEST unless 
589             $list and $list->owner == $e->requestor->id;
590     }
591
592     if($action eq 'delete') {
593         $success = $U->simplereq('open-ils.actor', 
594             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
595
596     } elsif($action eq 'show') {
597         unless($U->is_true($list->pub)) {
598             $list->pub('t');
599             $success = $U->simplereq('open-ils.actor', 
600                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
601         }
602
603     } elsif($action eq 'hide') {
604         if($U->is_true($list->pub)) {
605             $list->pub('f');
606             $success = $U->simplereq('open-ils.actor', 
607                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
608         }
609
610     } elsif($action eq 'rename') {
611         if($name) {
612             $list->name($name);
613             $success = $U->simplereq('open-ils.actor', 
614                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
615         }
616
617     } elsif($action eq 'add_rec') {
618         foreach my $add_rec (@add_rec) {
619             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
620             $item->bucket($list_id);
621             $item->target_biblio_record_entry($add_rec);
622             $success = $U->simplereq('open-ils.actor', 
623                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
624             last unless $success;
625         }
626
627     } elsif($action eq 'del_item') {
628         foreach (@del_item) {
629             $success = $U->simplereq(
630                 'open-ils.actor',
631                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
632             );
633             last unless $success;
634         }
635     }
636
637     return $self->generic_redirect if $success;
638
639     $self->ctx->{bucket_action} = $action;
640     $self->ctx->{bucket_action_failed} = 1;
641     return Apache2::Const::OK;
642 }
643
644 1