]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
92858eb59b6f88b23b6e80a235738bb88b7232fa
[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 use OpenILS::Event;
9 use OpenSRF::Utils::JSON;
10 use Data::Dumper;
11 $Data::Dumper::Indent = 0;
12 use DateTime;
13 my $U = 'OpenILS::Application::AppUtils';
14
15 sub prepare_extended_user_info {
16     my $self = shift;
17     my @extra_flesh = @_;
18
19     $self->ctx->{user} = $self->editor->retrieve_actor_user([
20         $self->ctx->{user}->id,
21         {
22             flesh => 1,
23             flesh_fields => {
24                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
25                 # ...
26             }
27         }
28     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
29
30     return;
31 }
32
33 # Given an event returned by a failed attempt to create a hold, do we have
34 # permission to override?  XXX Should the permission check be scoped to a
35 # given org_unit context?
36 sub test_could_override {
37     my ($self, $event) = @_;
38
39     return 0 unless $event;
40     return 1 if $self->editor->allowed($event->{textcode} . ".override");
41     return 1 if $event->{"fail_part"} and
42         $self->editor->allowed($event->{"fail_part"} . ".override");
43     return 0;
44 }
45
46 # Find out whether we care that local copies are available
47 sub local_avail_concern {
48     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
49
50     my $would_block = $self->ctx->{get_org_setting}->
51         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
52     my $would_alert = (
53         $self->ctx->{get_org_setting}->
54             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
55                 not $self->cgi->param("override")
56     ) unless $would_block;
57
58     if ($would_block or $would_alert) {
59         my $args = {
60             "hold_target" => $hold_target,
61             "hold_type" => $hold_type,
62             "org_unit" => $pickup_lib
63         };
64         my $local_avail = $U->simplereq(
65             "open-ils.circ",
66             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
67         );
68         $logger->info(
69             "copy availability information for " . Dumper($args) .
70             " is " . Dumper($local_avail)
71         );
72         if (%$local_avail) { # if hash not empty
73             $self->ctx->{hold_copy_available} = $local_avail;
74             return ($would_block, $would_alert);
75         }
76     }
77
78     return (0, 0);
79 }
80
81 # context additions: 
82 #   user : au object, fleshed
83 sub load_myopac_prefs {
84     my $self = shift;
85     my $cgi = $self->cgi;
86     my $e = $self->editor;
87     my $pending_addr = $cgi->param('pending_addr');
88     my $replace_addr = $cgi->param('replace_addr');
89     my $delete_pending = $cgi->param('delete_pending');
90
91     $self->prepare_extended_user_info;
92     my $user = $self->ctx->{user};
93
94     return Apache2::Const::OK unless 
95         $pending_addr or $replace_addr or $delete_pending;
96
97     my @form_fields = qw/address_type street1 street2 city county state country post_code/;
98
99     my $paddr;
100     if( $pending_addr ) { # update an existing pending address
101
102         ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
103         return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
104         $paddr->$_( $cgi->param($_) ) for @form_fields;
105
106     } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
107
108         $paddr = Fieldmapper::actor::user_address->new;
109         $paddr->isnew(1);
110         $paddr->usr($user->id);
111         $paddr->pending('t');
112         $paddr->replaces($replace_addr);
113         $paddr->$_( $cgi->param($_) ) for @form_fields;
114
115     } elsif( $delete_pending ) {
116         $paddr = $e->retrieve_actor_user_address($delete_pending);
117         return Apache2::Const::HTTP_BAD_REQUEST unless 
118             $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
119         $paddr->isdeleted(1);
120     }
121
122     my $resp = $U->simplereq(
123         'open-ils.actor', 
124         'open-ils.actor.user.address.pending.cud',
125         $e->authtoken, $paddr);
126
127     if( $U->event_code($resp) ) {
128         $logger->error("Error updating pending address: $resp");
129         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
130     }
131
132     # in light of these changes, re-fetch latest data
133     $e->xact_begin; 
134     $self->prepare_extended_user_info;
135     $e->rollback;
136
137     return Apache2::Const::OK;
138 }
139
140 sub load_myopac_prefs_notify {
141     my $self = shift;
142     my $e = $self->editor;
143
144     my $user_prefs = $self->fetch_optin_prefs;
145     $user_prefs = $self->update_optin_prefs($user_prefs)
146         if $self->cgi->request_method eq 'POST';
147
148     $self->ctx->{opt_in_settings} = $user_prefs; 
149
150     return Apache2::Const::OK;
151 }
152
153 sub fetch_optin_prefs {
154     my $self = shift;
155     my $e = $self->editor;
156
157     # fetch all of the opt-in settings the user has access to
158     # XXX: user's should in theory have options to opt-in to notices
159     # for remote locations, but that opens the door for a large
160     # set of generally un-used opt-ins.. needs discussion
161     my $opt_ins =  $U->simplereq(
162         'open-ils.actor',
163         'open-ils.actor.event_def.opt_in.settings.atomic',
164         $e->authtoken, $e->requestor->home_ou);
165
166     # some opt-ins are staff-only
167     $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
168
169     # fetch user setting values for each of the opt-in settings
170     my $user_set = $U->simplereq(
171         'open-ils.actor',
172         'open-ils.actor.patron.settings.retrieve',
173         $e->authtoken, 
174         $e->requestor->id, 
175         [map {$_->name} @$opt_ins]
176     );
177
178     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
179 }
180
181 sub update_optin_prefs {
182     my $self = shift;
183     my $user_prefs = shift;
184     my $e = $self->editor;
185     my @settings = $self->cgi->param('setting');
186     my %newsets;
187
188     # apply now-true settings
189     for my $applied (@settings) {
190         # see if setting is already applied to this user
191         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
192         $newsets{$applied} = OpenSRF::Utils::JSON->true;
193     }
194
195     # remove now-false settings
196     for my $pref (grep { $_->{value} } @$user_prefs) {
197         $newsets{$pref->{cust}->name} = undef 
198             unless grep { $_ eq $pref->{cust}->name } @settings;
199     }
200
201     $U->simplereq(
202         'open-ils.actor',
203         'open-ils.actor.patron.settings.update',
204         $e->authtoken, $e->requestor->id, \%newsets);
205
206     # update the local prefs to match reality
207     for my $pref (@$user_prefs) {
208         $pref->{value} = $newsets{$pref->{cust}->name} 
209             if exists $newsets{$pref->{cust}->name};
210     }
211
212     return $user_prefs;
213 }
214
215 sub _load_user_with_prefs {
216     my $self = shift;
217     my $stat = $self->prepare_extended_user_info('settings');
218     return $stat if $stat; # not-OK
219
220     $self->ctx->{user_setting_map} = {
221         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
222             @{$self->ctx->{user}->settings}
223     };
224
225     return undef;
226 }
227
228 sub load_myopac_prefs_settings {
229     my $self = shift;
230
231     my $stat = $self->_load_user_with_prefs;
232     return $stat if $stat;
233
234     return Apache2::Const::OK
235         unless $self->cgi->request_method eq 'POST';
236
237     # some setting values from the form don't match the 
238     # required value/format for the db, so they have to be 
239     # individually translated.
240
241     my %settings;
242     my $set_map = $self->ctx->{user_setting_map};
243
244     my $key = 'opac.hits_per_page';
245     my $val = $self->cgi->param($key);
246     $settings{$key}= $val unless $$set_map{$key} eq $val;
247
248     my $now = DateTime->now->strftime('%F');
249     for $key (qw/history.circ.retention_start history.hold.retention_start/) {
250         $val = $self->cgi->param($key);
251         if($val and $val eq 'on') {
252             # Set the start time to 'now' unless a start time already exists for the user
253             $settings{$key} = $now unless $$set_map{$key};
254         } else {
255             # clear the start time if one previously existed for the user
256             $settings{$key} = undef if $$set_map{$key};
257         }
258     }
259     
260     # Send the modified settings off to be saved
261     $U->simplereq(
262         'open-ils.actor', 
263         'open-ils.actor.patron.settings.update',
264         $self->editor->authtoken, undef, \%settings);
265
266     # re-fetch user prefs 
267     $self->ctx->{updated_user_settings} = \%settings;
268     return $self->_load_user_with_prefs || Apache2::Const::OK;
269 }
270
271 sub fetch_user_holds {
272     my $self = shift;
273     my $hold_ids = shift;
274     my $ids_only = shift;
275     my $flesh = shift;
276     my $available = shift;
277     my $limit = shift;
278     my $offset = shift;
279
280     my $e = $self->editor;
281
282     if(!$hold_ids) {
283         my $circ = OpenSRF::AppSession->create('open-ils.circ');
284
285         $hold_ids = $circ->request(
286             'open-ils.circ.holds.id_list.retrieve.authoritative', 
287             $e->authtoken, 
288             $e->requestor->id
289         )->gather(1);
290         $circ->kill_me;
291     
292         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
293     }
294
295
296     return $hold_ids if $ids_only or @$hold_ids == 0;
297
298     my $args = {
299         suppress_notices => 1,
300         suppress_transits => 1,
301         suppress_mvr => 1,
302         suppress_patron_details => 1,
303         include_bre => $flesh ? 1 : 0
304     };
305
306     # ----------------------------------------------------------------
307     # Collect holds in batches of $batch_size for faster retrieval
308
309     my $batch_size = 8;
310     my $batch_idx = 0;
311     my $mk_req_batch = sub {
312         my @ses;
313         my $top_idx = $batch_idx + $batch_size;
314         while($batch_idx < $top_idx) {
315             my $hold_id = $hold_ids->[$batch_idx++];
316             last unless $hold_id;
317             my $ses = OpenSRF::AppSession->create('open-ils.circ');
318             my $req = $ses->request(
319                 'open-ils.circ.hold.details.retrieve', 
320                 $e->authtoken, $hold_id, $args);
321             push(@ses, {ses => $ses, req => $req});
322         }
323         return @ses;
324     };
325
326     my $first = 1;
327     my(@collected, @holds, @ses);
328
329     while(1) {
330         @ses = $mk_req_batch->() if $first;
331         last if $first and not @ses;
332
333         if(@collected) {
334             # If desired by the caller, filter any holds that are not available.
335             if ($available) {
336                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
337             }
338             while(my $blob = pop(@collected)) {
339                 $blob->{marc_xml} = XML::LibXML->new->parse_string($blob->{hold}->{bre}->marc) if $flesh;
340                 push(@holds, $blob);
341             }
342         }
343
344         for my $req_data (@ses) {
345             push(@collected, {hold => $req_data->{req}->gather(1)});
346             $req_data->{ses}->kill_me;
347         }
348
349         @ses = $mk_req_batch->();
350         last unless @collected or @ses;
351         $first = 0;
352     }
353
354     # put the holds back into the original server sort order
355     my @sorted;
356     for my $id (@$hold_ids) {
357         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
358     }
359
360     return \@sorted;
361 }
362
363 sub handle_hold_update {
364     my $self = shift;
365     my $action = shift;
366     my $hold_ids = shift;
367     my $e = $self->editor;
368     my $url;
369
370     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
371     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
372
373     my $circ = OpenSRF::AppSession->create('open-ils.circ');
374
375     if($action =~ /cancel/) {
376
377         for my $hold_id (@hold_ids) {
378             my $resp = $circ->request(
379                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
380         }
381
382     } elsif ($action =~ /activate|suspend/) {
383         
384         my $vlist = [];
385         for my $hold_id (@hold_ids) {
386             my $vals = {id => $hold_id};
387
388             if($action =~ /activate/) {
389                 $vals->{frozen} = 'f';
390                 $vals->{thaw_date} = undef;
391
392             } elsif($action =~ /suspend/) {
393                 $vals->{frozen} = 't';
394                 # $vals->{thaw_date} = TODO;
395             }
396             push(@$vlist, $vals);
397         }
398
399         $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
400     } elsif ($action eq 'edit') {
401
402         my @vals = map {
403             my $val = {"id" => $_};
404             $val->{"frozen"} = $self->cgi->param("frozen");
405             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
406
407             for my $field (qw/expire_time thaw_date/) {
408                 # XXX TODO make this support other date formats, not just
409                 # MM/DD/YYYY.
410                 next unless $self->cgi->param($field) =~
411                     m:^(\d{2})/(\d{2})/(\d{4})$:;
412                 $val->{$field} = "$3-$1-$2";
413             }
414             $val;
415         } @hold_ids;
416
417         $circ->request(
418             'open-ils.circ.hold.update.batch.atomic',
419             $e->authtoken, undef, \@vals
420         )->gather(1);   # LFW XXX test for failure
421         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
422     }
423
424     $circ->kill_me;
425     return defined($url) ? $self->generic_redirect($url) : undef;
426 }
427
428 sub load_myopac_holds {
429     my $self = shift;
430     my $e = $self->editor;
431     my $ctx = $self->ctx;
432     
433     my $limit = $self->cgi->param('limit') || 0;
434     my $offset = $self->cgi->param('offset') || 0;
435     my $action = $self->cgi->param('action') || '';
436     my $hold_id = $self->cgi->param('id');
437     my $available = int($self->cgi->param('available') || 0);
438
439     my $hold_handle_result;
440     $hold_handle_result = $self->handle_hold_update($action) if $action;
441
442     $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
443
444     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
445 }
446
447 sub load_place_hold {
448     my $self = shift;
449     my $ctx = $self->ctx;
450     my $gos = $ctx->{get_org_setting};
451     my $e = $self->editor;
452     my $cgi = $self->cgi;
453
454     $self->ctx->{page} = 'place_hold';
455     my @targets = $cgi->param('hold_target');
456     $ctx->{hold_type} = $cgi->param('hold_type');
457     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
458
459     return $self->post_hold_redirect unless @targets;
460
461     $logger->info("Looking at hold targets: @targets");
462
463     # if the staff client provides a patron barcode, fetch the patron
464     if (my $bc = $self->cgi->cookie("patron_barcode")) {
465         $ctx->{patron_recipient} = $U->simplereq(
466             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
467             $self->editor->authtoken, $bc
468         ) or return Apache2::Const::HTTP_BAD_REQUEST;
469
470         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
471     }
472
473     my $request_lib = $e->requestor->ws_ou;
474     my @hold_data;
475     $ctx->{hold_data} = \@hold_data;
476
477     my $type_dispatch = {
478         T => sub {
479             my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
480             for my $id (@targets) { # force back into the correct order
481                 my ($rec) = grep {$_->id eq $id} @$recs;
482                 push(@hold_data, {target => $rec, record => $rec});
483             }
484         },
485         V => sub {
486             my $vols = $e->batch_retrieve_asset_call_number([
487                 \@targets, {
488                     "flesh" => 1,
489                     "flesh_fields" => {"acn" => ["record"]}
490                 }
491             ], {substream => 1});
492
493             for my $id (@targets) { 
494                 my ($vol) = grep {$_->id eq $id} @$vols;
495                 push(@hold_data, {target => $vol, record => $vol->record});
496             }
497         },
498         C => sub {
499             my $copies = $e->batch_retrieve_asset_copy([
500                 \@targets, {
501                     "flesh" => 2,
502                     "flesh_fields" => {
503                         "acn" => ["record"],
504                         "acp" => ["call_number"]
505                     }
506                 }
507             ], {substream => 1});
508
509             for my $id (@targets) { 
510                 my ($copy) = grep {$_->id eq $id} @$copies;
511                 push(@hold_data, {target => $copy, record => $copy->call_number->record});
512             }
513         },
514         I => sub {
515             my $isses = $e->batch_retrieve_serial_issuance([
516                 \@targets, {
517                     "flesh" => 2,
518                     "flesh_fields" => {
519                         "siss" => ["subscription"], "ssub" => ["record_entry"]
520                     }
521                 }
522             ], {substream => 1});
523
524             for my $id (@targets) { 
525                 my ($iss) = grep {$_->id eq $id} @$isses;
526                 push(@hold_data, {target => $iss, record => $iss->subscription->record_entry});
527             }
528         }
529         # ...
530
531     }->{$ctx->{hold_type}}->();
532
533     # caller sent bad target IDs or the wrong hold type
534     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
535
536     # generate the MARC xml for each record
537     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
538
539     my $pickup_lib = $cgi->param('pickup_lib');
540     # no pickup lib means no holds placement
541     return Apache2::Const::OK unless $pickup_lib;
542
543     $ctx->{hold_attempt_made} = 1;
544
545     # Give the original CGI params back to the user in case they
546     # want to try to override something.
547     $ctx->{orig_params} = $cgi->Vars;
548     delete $ctx->{orig_params}{submit};
549     delete $ctx->{orig_params}{hold_target};
550
551     my $usr = $e->requestor->id;
552
553     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
554         # find the real hold target
555
556         $usr = $U->simplereq(
557             'open-ils.actor', 
558             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
559             $e->authtoken, $cgi->param("hold_usr"));
560
561         if (defined $U->event_code($usr)) {
562             $ctx->{hold_failed} = 1;
563             $ctx->{hold_failed_event} = $usr;
564         }
565     }
566
567     # First see if we should warn/block for any holds that 
568     # might have locally available items.
569     for my $hdata (@hold_data) {
570         my ($local_block, $local_alert) = $self->local_avail_concern(
571             $hdata->{target}->id, $ctx->{hold_type}, $pickup_lib);
572     
573         if ($local_block) {
574             $hdata->{hold_failed} = 1;
575             $hdata->{hold_local_block} = 1;
576         } elsif ($local_alert) {
577             $hdata->{hold_failed} = 1;
578             $hdata->{hold_local_alert} = 1;
579         }
580     }
581
582
583     my $method = 'open-ils.circ.holds.test_and_create.batch';
584     $method .= '.override' if $cgi->param('override');
585
586     my @create_targets = map {$_->{target}->id} (grep { !$_->{hold_failed} } @hold_data);
587
588     if(@create_targets) {
589
590         my $bses = OpenSRF::AppSession->create('open-ils.circ');
591         my $breq = $bses->request( 
592             $method, 
593             $e->authtoken, 
594             {   patronid => $usr, 
595                 pickup_lib => $pickup_lib, 
596                 hold_type => $ctx->{hold_type}
597             }, 
598             \@create_targets
599         );
600
601         while (my $resp = $breq->recv) {
602
603             $resp = $resp->content;
604             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
605
606             if ($U->event_code($resp)) {
607                 $ctx->{general_hold_error} = $resp;
608                 last;
609             }
610
611             my ($hdata) = grep {$_->{target}->id eq $resp->{target}} @hold_data;
612             my $result = $resp->{result};
613
614             if ($U->event_code($result)) {
615                 # e.g. permission denied
616                 $hdata->{hold_failed} = 1;
617                 $hdata->{hold_failed_event} = $result;
618
619             } else {
620                 
621                 if(not ref $result and $result > 0) {
622                     # successul hold returns the hold ID
623
624                     $hdata->{hold_success} = $result; 
625     
626                 } else {
627                     # hold-specific failure event 
628                     $hdata->{hold_failed} = 1;
629                     $hdata->{hold_failed_event} = $result->{last_event};
630                     $hdata->{could_override} = $self->test_could_override($hdata->{hold_failed_event});
631                 }
632             }
633         }
634
635         $bses->kill_me;
636     }
637
638     # stay on the current page and display the results
639     return Apache2::Const::OK if 
640         (grep {$_->{hold_failed}} @hold_data) or $ctx->{general_hold_error};
641
642     # if successful, do some cleanup and return the 
643     # user to the requesting page.
644
645     return $self->post_hold_redirect;
646 }
647
648 sub post_hold_redirect {
649     my $self = shift;
650     
651     # XXX: Leave the barcode cookie in place.  Otherwise, it's not 
652     # possible to place more than one hold for the patron within 
653     # a staff/patron session.  This does leave the barcode to linger 
654     # longer than is ideal, but normal staff work flow will cause the 
655     # cookie to be replaced with each new patron anyway.
656     # TODO:  See about getting the staff client to clear the cookie
657     return $self->generic_redirect;
658
659     # We also clear the patron_barcode (from the staff client)
660     # cookie at this point (otherwise it haunts the staff user
661     # later). XXX todo make sure this is best; also see that
662     # template when staff mode calls xulG.opac_hold_placed()
663
664     return $self->generic_redirect(
665         undef,
666         $self->cgi->cookie(
667             -name => "patron_barcode",
668             -path => "/",
669             -secure => 1,
670             -value => "",
671             -expires => "-1h"
672         )
673     );
674 }
675
676
677 sub fetch_user_circs {
678     my $self = shift;
679     my $flesh = shift; # flesh bib data, etc.
680     my $circ_ids = shift;
681     my $limit = shift;
682     my $offset = shift;
683
684     my $e = $self->editor;
685
686     my @circ_ids;
687
688     if($circ_ids) {
689         @circ_ids = @$circ_ids;
690
691     } else {
692
693         my $circ_data = $U->simplereq(
694             'open-ils.actor', 
695             'open-ils.actor.user.checked_out',
696             $e->authtoken, 
697             $e->requestor->id
698         );
699
700         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
701
702         if($limit or $offset) {
703             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
704         }
705     }
706
707     return [] unless @circ_ids;
708
709     my $qflesh = {
710         flesh => 3,
711         flesh_fields => {
712             circ => ['target_copy'],
713             acp => ['call_number'],
714             acn => ['record']
715         }
716     };
717
718     $e->xact_begin;
719     my $circs = $e->search_action_circulation(
720         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
721
722     my @circs;
723     for my $circ (@$circs) {
724         push(@circs, {
725             circ => $circ, 
726             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
727                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
728                 undef  # pre-cat copy, use the dummy title/author instead
729         });
730     }
731     $e->xact_rollback;
732
733     # make sure the final list is in the correct order
734     my @sorted_circs;
735     for my $id (@circ_ids) {
736         push(
737             @sorted_circs,
738             (grep { $_->{circ}->id == $id } @circs)
739         );
740     }
741
742     return \@sorted_circs;
743 }
744
745
746 sub handle_circ_renew {
747     my $self = shift;
748     my $action = shift;
749     my $ctx = $self->ctx;
750
751     my @renew_ids = $self->cgi->param('circ');
752
753     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
754
755     # TODO: fire off renewal calls in batches to speed things up
756     my @responses;
757     for my $circ (@$circs) {
758
759         my $evt = $U->simplereq(
760             'open-ils.circ', 
761             'open-ils.circ.renew',
762             $self->editor->authtoken,
763             {
764                 patron_id => $self->editor->requestor->id,
765                 copy_id => $circ->{circ}->target_copy,
766                 opac_renewal => 1
767             }
768         );
769
770         # TODO return these, then insert them into the circ data 
771         # blob that is shoved into the template for each circ
772         # so the template won't have to match them
773         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
774     }
775
776     return @responses;
777 }
778
779
780 sub load_myopac_circs {
781     my $self = shift;
782     my $e = $self->editor;
783     my $ctx = $self->ctx;
784
785     $ctx->{circs} = [];
786     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
787     my $offset = $self->cgi->param('offset') || 0;
788     my $action = $self->cgi->param('action') || '';
789
790     # perform the renewal first if necessary
791     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
792
793     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
794
795     my $success_renewals = 0;
796     my $failed_renewals = 0;
797     for my $data (@{$ctx->{circs}}) {
798         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
799
800         if($resp) {
801             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
802             $data->{renewal_response} = $evt;
803             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
804             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
805         }
806     }
807
808     $ctx->{success_renewals} = $success_renewals;
809     $ctx->{failed_renewals} = $failed_renewals;
810
811     return Apache2::Const::OK;
812 }
813
814 sub load_myopac_circ_history {
815     my $self = shift;
816     my $e = $self->editor;
817     my $ctx = $self->ctx;
818     my $limit = $self->cgi->param('limit') || 15;
819     my $offset = $self->cgi->param('offset') || 0;
820
821     $ctx->{circ_history_limit} = $limit;
822     $ctx->{circ_history_offset} = $offset;
823
824     my $circ_ids = $e->json_query({
825         select => {
826             au => [{
827                 column => 'id', 
828                 transform => 'action.usr_visible_circs', 
829                 result_field => 'id'
830             }]
831         },
832         from => 'au',
833         where => {id => $e->requestor->id}, 
834         limit => $limit,
835         offset => $offset
836     });
837
838     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
839     return Apache2::Const::OK;
840 }
841
842 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
843 sub load_myopac_hold_history {
844     my $self = shift;
845     my $e = $self->editor;
846     my $ctx = $self->ctx;
847     my $limit = $self->cgi->param('limit') || 15;
848     my $offset = $self->cgi->param('offset') || 0;
849     $ctx->{hold_history_limit} = $limit;
850     $ctx->{hold_history_offset} = $offset;
851
852     my $hold_ids = $e->json_query({
853         select => {
854             au => [{
855                 column => 'id', 
856                 transform => 'action.usr_visible_holds', 
857                 result_field => 'id'
858             }]
859         },
860         from => 'au',
861         where => {id => $e->requestor->id}, 
862         limit => $limit,
863         offset => $offset
864     });
865
866     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
867     return Apache2::Const::OK;
868 }
869
870 sub load_myopac_payment_form {
871     my $self = shift;
872     my $r;
873
874     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
875     $r = $self->prepare_extended_user_info and return $r;
876
877     return Apache2::Const::OK;
878 }
879
880 # TODO: add other filter options as params/configs/etc.
881 sub load_myopac_payments {
882     my $self = shift;
883     my $limit = $self->cgi->param('limit') || 20;
884     my $offset = $self->cgi->param('offset') || 0;
885     my $e = $self->editor;
886
887     $self->ctx->{payment_history_limit} = $limit;
888     $self->ctx->{payment_history_offset} = $offset;
889
890     my $args = {};
891     $args->{limit} = $limit if $limit;
892     $args->{offset} = $offset if $offset;
893
894     if (my $max_age = $self->ctx->{get_org_setting}->(
895         $e->requestor->home_ou, "opac.payment_history_age_limit"
896     )) {
897         my $min_ts = DateTime->now(
898             "time_zone" => DateTime::TimeZone->new("name" => "local"),
899         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
900         
901         $logger->info("XXX min_ts: $min_ts");
902         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
903     }
904
905     $self->ctx->{payments} = $U->simplereq(
906         'open-ils.actor',
907         'open-ils.actor.user.payments.retrieve.atomic',
908         $e->authtoken, $e->requestor->id, $args);
909
910     return Apache2::Const::OK;
911 }
912
913 sub load_myopac_pay {
914     my $self = shift;
915     my $r;
916
917     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and
918         return $r;
919
920     # balance_owed is computed specifically from the fines we're trying
921     # to pay in this case.
922     if ($self->ctx->{fines}->{balance_owed} <= 0) {
923         $self->apache->log->info(
924             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
925                 join(", ", map(int, $self->cgi->param("xact"), $self->cgi->param('xact_misc'))))
926         );
927         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
928     }
929
930     my $cc_args = {"where_process" => 1};
931
932     $cc_args->{$_} = $self->cgi->param($_) for (qw/
933         number cvv2 expire_year expire_month billing_first
934         billing_last billing_address billing_city billing_state
935         billing_zip
936     /);
937
938     my $args = {
939         "cc_args" => $cc_args,
940         "userid" => $self->ctx->{user}->id,
941         "payment_type" => "credit_card_payment",
942         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
943     };
944
945     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
946         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
947     );
948
949     $self->ctx->{"payment_response"} = $resp;
950
951     unless ($resp->{"textcode"}) {
952         $self->ctx->{printable_receipt} = $U->simplereq(
953            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
954            $self->editor->authtoken, $resp->{payments}
955         );
956     }
957
958     return Apache2::Const::OK;
959 }
960
961 sub load_myopac_receipt_print {
962     my $self = shift;
963
964     $self->ctx->{printable_receipt} = $U->simplereq(
965        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
966        $self->editor->authtoken, [$self->cgi->param("payment")]
967     );
968
969     return Apache2::Const::OK;
970 }
971
972 sub load_myopac_receipt_email {
973     my $self = shift;
974
975     # The following ML method doesn't actually check whether the user in
976     # question has an email address, so we do.
977     if ($self->ctx->{user}->email) {
978         $self->ctx->{email_receipt_result} = $U->simplereq(
979            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
980            $self->editor->authtoken, [$self->cgi->param("payment")]
981         );
982     } else {
983         $self->ctx->{email_receipt_result} =
984             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
985     }
986
987     return Apache2::Const::OK;
988 }
989
990 sub prepare_fines {
991     my ($self, $limit, $offset, $id_list) = @_;
992
993     # XXX TODO: check for failure after various network calls
994
995     # It may be unclear, but this result structure lumps circulation and
996     # reservation fines together, and keeps grocery fines separate.
997     $self->ctx->{"fines"} = {
998         "circulation" => [],
999         "grocery" => [],
1000         "total_paid" => 0,
1001         "total_owed" => 0,
1002         "balance_owed" => 0
1003     };
1004
1005     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1006
1007     # TODO: This should really be a ML call, but the existing calls 
1008     # return an excessive amount of data and don't offer streaming
1009
1010     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1011
1012     my $req = $cstore->request(
1013         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1014         {
1015             usr => $self->editor->requestor->id,
1016             balance_owed => {'!=' => 0},
1017             ($id_list && @$id_list ? ("id" => $id_list) : ()),
1018         },
1019         {
1020             flesh => 4,
1021             flesh_fields => {
1022                 mobts => [qw/grocery circulation reservation/],
1023                 bresv => ['target_resource_type'],
1024                 brt => ['record'],
1025                 mg => ['billings'],
1026                 mb => ['btype'],
1027                 circ => ['target_copy'],
1028                 acp => ['call_number'],
1029                 acn => ['record']
1030             },
1031             order_by => { mobts => 'xact_start' },
1032             %paging
1033         }
1034     );
1035
1036     my @total_keys = qw/total_paid total_owed balance_owed/;
1037     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1038
1039     while(my $resp = $req->recv) {
1040         my $mobts = $resp->content;
1041         my $circ = $mobts->circulation;
1042
1043         my $last_billing;
1044         if($mobts->grocery) {
1045             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1046             $last_billing = pop(@billings);
1047         }
1048
1049         # XXX TODO confirm that the following, and the later division by 100.0
1050         # to get a floating point representation once again, is sufficiently
1051         # "money-safe" math.
1052         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1053
1054         my $marc_xml = undef;
1055         if ($mobts->xact_type eq 'reservation' and
1056             $mobts->reservation->target_resource_type->record) {
1057             $marc_xml = XML::LibXML->new->parse_string(
1058                 $mobts->reservation->target_resource_type->record->marc
1059             );
1060         } elsif ($mobts->xact_type eq 'circulation' and
1061             $circ->target_copy->call_number->id != -1) {
1062             $marc_xml = XML::LibXML->new->parse_string(
1063                 $circ->target_copy->call_number->record->marc
1064             );
1065         }
1066
1067         push(
1068             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1069             {
1070                 xact => $mobts,
1071                 last_grocery_billing => $last_billing,
1072                 marc_xml => $marc_xml
1073             } 
1074         );
1075     }
1076
1077     $cstore->kill_me;
1078
1079     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1080     return;
1081 }
1082
1083 sub prepare_fines_for_payment {
1084     # This assumes $self->prepare_fines has already been run
1085     my ($self) = @_;
1086
1087     my @results = ();
1088     if ($self->ctx->{fines}) {
1089         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1090             @{$self->ctx->{fines}->{circulation}},
1091             @{$self->ctx->{fines}->{grocery}}
1092         );
1093     }
1094
1095     return \@results;
1096 }
1097
1098 sub load_myopac_main {
1099     my $self = shift;
1100     my $limit = $self->cgi->param('limit') || 0;
1101     my $offset = $self->cgi->param('offset') || 0;
1102
1103     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1104 }
1105
1106 sub load_myopac_update_email {
1107     my $self = shift;
1108     my $e = $self->editor;
1109     my $ctx = $self->ctx;
1110     my $email = $self->cgi->param('email') || '';
1111
1112     # needed for most up-to-date email address
1113     if (my $r = $self->prepare_extended_user_info) { return $r };
1114
1115     return Apache2::Const::OK 
1116         unless $self->cgi->request_method eq 'POST';
1117
1118     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1119         $ctx->{invalid_email} = $email;
1120         return Apache2::Const::OK;
1121     }
1122
1123     my $stat = $U->simplereq(
1124         'open-ils.actor', 
1125         'open-ils.actor.user.email.update', 
1126         $e->authtoken, $email);
1127
1128     unless ($self->cgi->param("redirect_to")) {
1129         my $url = $self->apache->unparsed_uri;
1130         $url =~ s/update_email/prefs/;
1131
1132         return $self->generic_redirect($url);
1133     }
1134
1135     return $self->generic_redirect;
1136 }
1137
1138 sub load_myopac_update_username {
1139     my $self = shift;
1140     my $e = $self->editor;
1141     my $ctx = $self->ctx;
1142     my $username = $self->cgi->param('username') || '';
1143
1144     return Apache2::Const::OK 
1145         unless $self->cgi->request_method eq 'POST';
1146
1147     unless($username and $username !~ /\s/) { # any other username restrictions?
1148         $ctx->{invalid_username} = $username;
1149         return Apache2::Const::OK;
1150     }
1151
1152     if($username ne $e->requestor->usrname) {
1153
1154         my $evt = $U->simplereq(
1155             'open-ils.actor', 
1156             'open-ils.actor.user.username.update', 
1157             $e->authtoken, $username);
1158
1159         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1160             $ctx->{username_exists} = $username;
1161             return Apache2::Const::OK;
1162         }
1163     }
1164
1165     my $url = $self->apache->unparsed_uri;
1166     $url =~ s/update_username/prefs/;
1167
1168     return $self->generic_redirect($url);
1169 }
1170
1171 sub load_myopac_update_password {
1172     my $self = shift;
1173     my $e = $self->editor;
1174     my $ctx = $self->ctx;
1175
1176     return Apache2::Const::OK 
1177         unless $self->cgi->request_method eq 'POST';
1178
1179     my $current_pw = $self->cgi->param('current_pw') || '';
1180     my $new_pw = $self->cgi->param('new_pw') || '';
1181     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1182
1183     unless($new_pw eq $new_pw2) {
1184         $ctx->{password_nomatch} = 1;
1185         return Apache2::Const::OK;
1186     }
1187
1188     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1189
1190     if($pw_regex and $new_pw !~ /$pw_regex/) {
1191         $ctx->{password_invalid} = 1;
1192         return Apache2::Const::OK;
1193     }
1194
1195     my $evt = $U->simplereq(
1196         'open-ils.actor', 
1197         'open-ils.actor.user.password.update', 
1198         $e->authtoken, $new_pw, $current_pw);
1199
1200
1201     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1202         $ctx->{password_incorrect} = 1;
1203         return Apache2::Const::OK;
1204     }
1205
1206     my $url = $self->apache->unparsed_uri;
1207     $url =~ s/update_password/prefs/;
1208
1209     return $self->generic_redirect($url);
1210 }
1211
1212 sub load_myopac_bookbags {
1213     my $self = shift;
1214     my $e = $self->editor;
1215     my $ctx = $self->ctx;
1216
1217     $e->xact_begin; # replication...
1218
1219     my $rv = $self->load_mylist;
1220     unless($rv eq Apache2::Const::OK) {
1221         $e->rollback;
1222         return $rv;
1223     }
1224
1225     my $args = {
1226         order_by => {cbreb => 'name'},
1227         limit => $self->cgi->param('limit') || 10,
1228         offset => $self->cgi->param('offset') || 0
1229     };
1230
1231     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1232         [
1233             {owner => $self->editor->requestor->id, btype => 'bookbag'},
1234             {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
1235         ], 
1236         {substream => 1}
1237     );
1238
1239     if(!$ctx->{bookbags}) {
1240         $e->rollback;
1241         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1242     }
1243     
1244     # get unique record IDs
1245     my %rec_ids = ();
1246     foreach my $bbag (@{$ctx->{bookbags}}) {
1247         foreach my $rec_id (
1248             map { $_->target_biblio_record_entry } @{$bbag->items}
1249         ) {
1250             $rec_ids{$rec_id} = 1;
1251         }
1252     }
1253
1254     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
1255
1256     $e->rollback;
1257     return Apache2::Const::OK;
1258 }
1259
1260
1261 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1262 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1263 sub load_myopac_bookbag_update {
1264     my ($self, $action, $list_id, @hold_recs) = @_;
1265     my $e = $self->editor;
1266     my $cgi = $self->cgi;
1267
1268     $action ||= $cgi->param('action');
1269     $list_id ||= $cgi->param('list');
1270
1271     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1272     my @selected_item = $cgi->param('selected_item');
1273     my $shared = $cgi->param('shared');
1274     my $name = $cgi->param('name');
1275     my $success = 0;
1276     my $list;
1277
1278     if($action eq 'create') {
1279         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1280         $list->name($name);
1281         $list->owner($e->requestor->id);
1282         $list->btype('bookbag');
1283         $list->pub($shared ? 't' : 'f');
1284         $success = $U->simplereq('open-ils.actor', 
1285             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1286
1287     } elsif($action eq 'place_hold') {
1288
1289         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1290         unless (@hold_recs) {
1291             if (@selected_item) {
1292                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1293                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1294             }
1295         }
1296                 
1297         return Apache2::Const::OK unless @hold_recs;
1298         $logger->info("placing holds from list page on: @hold_recs");
1299
1300         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1301         $url .= ';hold_target=' . $_ for @hold_recs;
1302         return $self->generic_redirect($url);
1303
1304     } else {
1305
1306         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1307
1308         return Apache2::Const::HTTP_BAD_REQUEST unless 
1309             $list and $list->owner == $e->requestor->id;
1310     }
1311
1312     if($action eq 'delete') {
1313         $success = $U->simplereq('open-ils.actor', 
1314             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1315
1316     } elsif($action eq 'show') {
1317         unless($U->is_true($list->pub)) {
1318             $list->pub('t');
1319             $success = $U->simplereq('open-ils.actor', 
1320                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1321         }
1322
1323     } elsif($action eq 'hide') {
1324         if($U->is_true($list->pub)) {
1325             $list->pub('f');
1326             $success = $U->simplereq('open-ils.actor', 
1327                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1328         }
1329
1330     } elsif($action eq 'rename') {
1331         if($name) {
1332             $list->name($name);
1333             $success = $U->simplereq('open-ils.actor', 
1334                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1335         }
1336
1337     } elsif($action eq 'add_rec') {
1338         foreach my $add_rec (@add_rec) {
1339             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1340             $item->bucket($list_id);
1341             $item->target_biblio_record_entry($add_rec);
1342             $success = $U->simplereq('open-ils.actor', 
1343                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1344             last unless $success;
1345         }
1346
1347     } elsif($action eq 'del_item') {
1348         foreach (@selected_item) {
1349             $success = $U->simplereq(
1350                 'open-ils.actor',
1351                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1352             );
1353             last unless $success;
1354         }
1355     }
1356
1357     return $self->generic_redirect if $success;
1358
1359     $self->ctx->{bucket_action} = $action;
1360     $self->ctx->{bucket_action_failed} = 1;
1361     return Apache2::Const::OK;
1362 }
1363
1364 1