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