]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
Add PLACE_UNFILLABLE_HOLD permission
[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 OpenSRF::Utils::Cache;
11 use Digest::MD5 qw(md5_hex);
12 use Data::Dumper;
13 $Data::Dumper::Indent = 0;
14 use DateTime;
15 my $U = 'OpenILS::Application::AppUtils';
16
17 sub prepare_extended_user_info {
18     my $self = shift;
19     my @extra_flesh = @_;
20     my $e = $self->editor;
21
22     # are we already in a transaction?
23     my $local_xact = !$e->{xact_id}; 
24     $e->xact_begin if $local_xact;
25
26     $self->ctx->{user} = $self->editor->retrieve_actor_user([
27         $self->ctx->{user}->id,
28         {
29             flesh => 1,
30             flesh_fields => {
31                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
32                 # ...
33             }
34         }
35     ]);
36
37     $e->rollback if $local_xact;
38
39     # discard replaced (negative-id) addresses.
40     $self->ctx->{user}->addresses([
41         grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
42
43     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR 
44         unless $self->ctx->{user};
45
46     return;
47 }
48
49 # Given an event returned by a failed attempt to create a hold, do we have
50 # permission to override?  XXX Should the permission check be scoped to a
51 # given org_unit context?
52 sub test_could_override {
53     my ($self, $event) = @_;
54
55     return 0 unless $event;
56     return 1 if $self->editor->allowed($event->{textcode} . ".override");
57     return 1 if $event->{"fail_part"} and
58         $self->editor->allowed($event->{"fail_part"} . ".override");
59     return 0;
60 }
61
62 # Find out whether we care that local copies are available
63 sub local_avail_concern {
64     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
65
66     my $would_block = $self->ctx->{get_org_setting}->
67         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
68     my $would_alert = (
69         $self->ctx->{get_org_setting}->
70             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
71                 not $self->cgi->param("override")
72     ) unless $would_block;
73
74     if ($would_block or $would_alert) {
75         my $args = {
76             "hold_target" => $hold_target,
77             "hold_type" => $hold_type,
78             "org_unit" => $pickup_lib
79         };
80         my $local_avail = $U->simplereq(
81             "open-ils.circ",
82             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
83         );
84         $logger->info(
85             "copy availability information for " . Dumper($args) .
86             " is " . Dumper($local_avail)
87         );
88         if (%$local_avail) { # if hash not empty
89             $self->ctx->{hold_copy_available} = $local_avail;
90             return ($would_block, $would_alert);
91         }
92     }
93
94     return (0, 0);
95 }
96
97 # context additions: 
98 #   user : au object, fleshed
99 sub load_myopac_prefs {
100     my $self = shift;
101     my $cgi = $self->cgi;
102     my $e = $self->editor;
103     my $pending_addr = $cgi->param('pending_addr');
104     my $replace_addr = $cgi->param('replace_addr');
105     my $delete_pending = $cgi->param('delete_pending');
106
107     $self->prepare_extended_user_info;
108     my $user = $self->ctx->{user};
109
110     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
111     if($lock_usernames == 1) {
112         # Policy says no username changes
113         $self->ctx->{username_change_disallowed} = 1;
114     } else {
115         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
116         if($username_unlimit != 1) {
117             my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
118             if(!$regex_check) {
119                 # Default is "starts with a number"
120                 $regex_check = '^\d+';
121             }
122             # You already have a username?
123             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
124                 $self->ctx->{username_change_disallowed} = 1;
125             }
126         }
127     }
128
129     return Apache2::Const::OK unless 
130         $pending_addr or $replace_addr or $delete_pending;
131
132     my @form_fields = qw/address_type street1 street2 city county state country post_code/;
133
134     my $paddr;
135     if( $pending_addr ) { # update an existing pending address
136
137         ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
138         return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
139         $paddr->$_( $cgi->param($_) ) for @form_fields;
140
141     } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
142
143         $paddr = Fieldmapper::actor::user_address->new;
144         $paddr->isnew(1);
145         $paddr->usr($user->id);
146         $paddr->pending('t');
147         $paddr->replaces($replace_addr);
148         $paddr->$_( $cgi->param($_) ) for @form_fields;
149
150     } elsif( $delete_pending ) {
151         $paddr = $e->retrieve_actor_user_address($delete_pending);
152         return Apache2::Const::HTTP_BAD_REQUEST unless 
153             $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
154         $paddr->isdeleted(1);
155     }
156
157     my $resp = $U->simplereq(
158         'open-ils.actor', 
159         'open-ils.actor.user.address.pending.cud',
160         $e->authtoken, $paddr);
161
162     if( $U->event_code($resp) ) {
163         $logger->error("Error updating pending address: $resp");
164         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
165     }
166
167     # in light of these changes, re-fetch latest data
168     $e->xact_begin; 
169     $self->prepare_extended_user_info;
170     $e->rollback;
171
172     return Apache2::Const::OK;
173 }
174
175 sub load_myopac_prefs_notify {
176     my $self = shift;
177     my $e = $self->editor;
178
179     my $user_prefs = $self->fetch_optin_prefs;
180     $user_prefs = $self->update_optin_prefs($user_prefs)
181         if $self->cgi->request_method eq 'POST';
182
183     $self->ctx->{opt_in_settings} = $user_prefs;
184
185     my %settings;
186     my $set_map = $self->ctx->{user_setting_map};
187  
188     foreach my $key (qw/
189         opac.default_phone
190         opac.default_sms_notify
191     /) {
192         my $val = $self->cgi->param($key);
193         $settings{$key}= $val unless $$set_map{$key} eq $val;
194     }
195
196     my $key = 'opac.default_sms_carrier';
197     my $val = $self->cgi->param('sms_carrier');
198     $settings{$key}= $val unless $$set_map{$key} eq $val;
199
200     $key = 'opac.hold_notify';
201     my @notify_methods = ();
202     if ($self->cgi->param($key . ".email") eq 'on') {
203         push @notify_methods, "email";
204     }
205     if ($self->cgi->param($key . ".phone") eq 'on') {
206         push @notify_methods, "phone";
207     }
208     if ($self->cgi->param($key . ".sms") eq 'on') {
209         push @notify_methods, "sms";
210     }
211     $val = join("|",@notify_methods);
212     $settings{$key}= $val unless $$set_map{$key} eq $val;
213
214     # Send the modified settings off to be saved
215     $U->simplereq(
216         'open-ils.actor', 
217         'open-ils.actor.patron.settings.update',
218         $self->editor->authtoken, undef, \%settings);
219
220     # re-fetch user prefs 
221     $self->ctx->{updated_user_settings} = \%settings;
222     return $self->_load_user_with_prefs || Apache2::Const::OK;
223 }
224
225 sub fetch_optin_prefs {
226     my $self = shift;
227     my $e = $self->editor;
228
229     # fetch all of the opt-in settings the user has access to
230     # XXX: user's should in theory have options to opt-in to notices
231     # for remote locations, but that opens the door for a large
232     # set of generally un-used opt-ins.. needs discussion
233     my $opt_ins =  $U->simplereq(
234         'open-ils.actor',
235         'open-ils.actor.event_def.opt_in.settings.atomic',
236         $e->authtoken, $e->requestor->home_ou);
237
238     # some opt-ins are staff-only
239     $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
240
241     # fetch user setting values for each of the opt-in settings
242     my $user_set = $U->simplereq(
243         'open-ils.actor',
244         'open-ils.actor.patron.settings.retrieve',
245         $e->authtoken, 
246         $e->requestor->id, 
247         [map {$_->name} @$opt_ins]
248     );
249
250     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
251 }
252
253 sub update_optin_prefs {
254     my $self = shift;
255     my $user_prefs = shift;
256     my $e = $self->editor;
257     my @settings = $self->cgi->param('setting');
258     my %newsets;
259
260     # apply now-true settings
261     for my $applied (@settings) {
262         # see if setting is already applied to this user
263         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
264         $newsets{$applied} = OpenSRF::Utils::JSON->true;
265     }
266
267     # remove now-false settings
268     for my $pref (grep { $_->{value} } @$user_prefs) {
269         $newsets{$pref->{cust}->name} = undef 
270             unless grep { $_ eq $pref->{cust}->name } @settings;
271     }
272
273     $U->simplereq(
274         'open-ils.actor',
275         'open-ils.actor.patron.settings.update',
276         $e->authtoken, $e->requestor->id, \%newsets);
277
278     # update the local prefs to match reality
279     for my $pref (@$user_prefs) {
280         $pref->{value} = $newsets{$pref->{cust}->name} 
281             if exists $newsets{$pref->{cust}->name};
282     }
283
284     return $user_prefs;
285 }
286
287 sub _load_user_with_prefs {
288     my $self = shift;
289     my $stat = $self->prepare_extended_user_info('settings');
290     return $stat if $stat; # not-OK
291
292     $self->ctx->{user_setting_map} = {
293         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
294             @{$self->ctx->{user}->settings}
295     };
296
297     return undef;
298 }
299
300 sub _get_bookbag_sort_params {
301     my ($self, $param_name) = @_;
302
303     # The interface that feeds this cgi parameter will provide a single
304     # argument for a QP sort filter, and potentially a modifier after a period.
305     # In practice this means the "sort" parameter will be something like
306     # "titlesort" or "authorsort.descending".
307     my $sorter = $self->cgi->param($param_name) || "";
308     my $modifier;
309     if ($sorter) {
310         $sorter =~ s/^(.*?)\.(.*)/$1/;
311         $modifier = $2 || undef;
312     }
313
314     return ($sorter, $modifier);
315 }
316
317 sub _prepare_bookbag_container_query {
318     my ($self, $container_id, $sorter, $modifier) = @_;
319
320     return sprintf(
321         "container(bre,bookbag,%d,%s)%s%s",
322         $container_id, $self->editor->authtoken,
323         ($sorter ? " sort($sorter)" : ""),
324         ($modifier ? "#$modifier" : "")
325     );
326 }
327
328 sub _prepare_anonlist_sorting_query {
329     my ($self, $list, $sorter, $modifier) = @_;
330
331     return sprintf(
332         "record_list(%s)%s%s",
333         join(",", @$list),
334         ($sorter ? " sort($sorter)" : ""),
335         ($modifier ? "#$modifier" : "")
336     );
337 }
338
339
340 sub load_myopac_prefs_settings {
341     my $self = shift;
342
343     my @user_prefs = qw/
344         opac.hits_per_page
345         opac.default_search_location
346     /;
347
348     my $stat = $self->_load_user_with_prefs;
349     return $stat if $stat;
350
351     return Apache2::Const::OK
352         unless $self->cgi->request_method eq 'POST';
353
354     # some setting values from the form don't match the 
355     # required value/format for the db, so they have to be 
356     # individually translated.
357
358     my %settings;
359     my $set_map = $self->ctx->{user_setting_map};
360
361     foreach my $key (@user_prefs) {
362         my $val = $self->cgi->param($key);
363         $settings{$key}= $val unless $$set_map{$key} eq $val;
364     }
365
366     my $now = DateTime->now->strftime('%F');
367     foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
368         my $val = $self->cgi->param($key);
369         if($val and $val eq 'on') {
370             # Set the start time to 'now' unless a start time already exists for the user
371             $settings{$key} = $now unless $$set_map{$key};
372         } else {
373             # clear the start time if one previously existed for the user
374             $settings{$key} = undef if $$set_map{$key};
375         }
376     }
377
378     # Send the modified settings off to be saved
379     $U->simplereq(
380         'open-ils.actor', 
381         'open-ils.actor.patron.settings.update',
382         $self->editor->authtoken, undef, \%settings);
383
384     # re-fetch user prefs 
385     $self->ctx->{updated_user_settings} = \%settings;
386     return $self->_load_user_with_prefs || Apache2::Const::OK;
387 }
388
389 sub fetch_user_holds {
390     my $self = shift;
391     my $hold_ids = shift;
392     my $ids_only = shift;
393     my $flesh = shift;
394     my $available = shift;
395     my $limit = shift;
396     my $offset = shift;
397
398     my $e = $self->editor;
399
400     if(!$hold_ids) {
401         my $circ = OpenSRF::AppSession->create('open-ils.circ');
402
403         $hold_ids = $circ->request(
404             'open-ils.circ.holds.id_list.retrieve.authoritative', 
405             $e->authtoken, 
406             $e->requestor->id
407         )->gather(1);
408         $circ->kill_me;
409     
410         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
411     }
412
413
414     return $hold_ids if $ids_only or @$hold_ids == 0;
415
416     my $args = {
417         suppress_notices => 1,
418         suppress_transits => 1,
419         suppress_mvr => 1,
420         suppress_patron_details => 1
421     };
422
423     # ----------------------------------------------------------------
424     # Collect holds in batches of $batch_size for faster retrieval
425
426     my $batch_size = 8;
427     my $batch_idx = 0;
428     my $mk_req_batch = sub {
429         my @ses;
430         my $top_idx = $batch_idx + $batch_size;
431         while($batch_idx < $top_idx) {
432             my $hold_id = $hold_ids->[$batch_idx++];
433             last unless $hold_id;
434             my $ses = OpenSRF::AppSession->create('open-ils.circ');
435             my $req = $ses->request(
436                 'open-ils.circ.hold.details.retrieve', 
437                 $e->authtoken, $hold_id, $args);
438             push(@ses, {ses => $ses, req => $req});
439         }
440         return @ses;
441     };
442
443     my $first = 1;
444     my(@collected, @holds, @ses);
445
446     while(1) {
447         @ses = $mk_req_batch->() if $first;
448         last if $first and not @ses;
449
450         if(@collected) {
451             # If desired by the caller, filter any holds that are not available.
452             if ($available) {
453                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
454             }
455             while(my $blob = pop(@collected)) {
456                 my (undef, @data) = $self->get_records_and_facets(
457                     [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
458                 );
459                 $blob->{marc_xml} = $data[0]->{marc_xml};
460                 push(@holds, $blob);
461             }
462         }
463
464         for my $req_data (@ses) {
465             push(@collected, {hold => $req_data->{req}->gather(1)});
466             $req_data->{ses}->kill_me;
467         }
468
469         @ses = $mk_req_batch->();
470         last unless @collected or @ses;
471         $first = 0;
472     }
473
474     # put the holds back into the original server sort order
475     my @sorted;
476     for my $id (@$hold_ids) {
477         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
478     }
479
480     return \@sorted;
481 }
482
483 sub handle_hold_update {
484     my $self = shift;
485     my $action = shift;
486     my $hold_ids = shift;
487     my $e = $self->editor;
488     my $url;
489
490     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
491     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
492
493     my $circ = OpenSRF::AppSession->create('open-ils.circ');
494
495     if($action =~ /cancel/) {
496
497         for my $hold_id (@hold_ids) {
498             my $resp = $circ->request(
499                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
500         }
501
502     } elsif ($action =~ /activate|suspend/) {
503         
504         my $vlist = [];
505         for my $hold_id (@hold_ids) {
506             my $vals = {id => $hold_id};
507
508             if($action =~ /activate/) {
509                 $vals->{frozen} = 'f';
510                 $vals->{thaw_date} = undef;
511
512             } elsif($action =~ /suspend/) {
513                 $vals->{frozen} = 't';
514                 # $vals->{thaw_date} = TODO;
515             }
516             push(@$vlist, $vals);
517         }
518
519         my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
520         $self->ctx->{hold_suspend_post_capture} = 1 if 
521             grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
522
523     } elsif ($action eq 'edit') {
524
525         my @vals = map {
526             my $val = {"id" => $_};
527             $val->{"frozen"} = $self->cgi->param("frozen");
528             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
529
530             for my $field (qw/expire_time thaw_date/) {
531                 # XXX TODO make this support other date formats, not just
532                 # MM/DD/YYYY.
533                 next unless $self->cgi->param($field) =~
534                     m:^(\d{2})/(\d{2})/(\d{4})$:;
535                 $val->{$field} = "$3-$1-$2";
536             }
537             $val;
538         } @hold_ids;
539
540         $circ->request(
541             'open-ils.circ.hold.update.batch.atomic',
542             $e->authtoken, undef, \@vals
543         )->gather(1);   # LFW XXX test for failure
544         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
545         foreach my $param (('loc', 'qtype', 'query')) {
546             if ($self->cgi->param($param)) {
547                 $url .= ";$param=" . uri_escape($self->cgi->param($param));
548             }
549         }
550     }
551
552     $circ->kill_me;
553     return defined($url) ? $self->generic_redirect($url) : undef;
554 }
555
556 sub load_myopac_holds {
557     my $self = shift;
558     my $e = $self->editor;
559     my $ctx = $self->ctx;
560     
561     my $limit = $self->cgi->param('limit') || 0;
562     my $offset = $self->cgi->param('offset') || 0;
563     my $action = $self->cgi->param('action') || '';
564     my $hold_id = $self->cgi->param('id');
565     my $available = int($self->cgi->param('available') || 0);
566
567     my $hold_handle_result;
568     $hold_handle_result = $self->handle_hold_update($action) if $action;
569
570     $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
571
572     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
573 }
574
575 my $data_filler;
576
577 sub load_place_hold {
578     my $self = shift;
579     my $ctx = $self->ctx;
580     my $gos = $ctx->{get_org_setting};
581     my $e = $self->editor;
582     my $cgi = $self->cgi;
583
584     $self->ctx->{page} = 'place_hold';
585     my @targets = $cgi->param('hold_target');
586     my @parts = $cgi->param('part');
587
588     $ctx->{hold_type} = $cgi->param('hold_type');
589     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
590     $ctx->{email_notify} = $cgi->param('email_notify');
591     if ($cgi->param('phone_notify_checkbox')) {
592         $ctx->{phone_notify} = $cgi->param('phone_notify');
593     }
594     if ($cgi->param('sms_notify_checkbox')) {
595         $ctx->{sms_notify} = $cgi->param('sms_notify');
596         $ctx->{sms_carrier} = $cgi->param('sms_carrier');
597     }
598
599     return $self->generic_redirect unless @targets;
600
601     $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
602
603     # if the staff client provides a patron barcode, fetch the patron
604     if (my $bc = $self->cgi->cookie("patron_barcode")) {
605         $ctx->{patron_recipient} = $U->simplereq(
606             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
607             $self->editor->authtoken, $bc
608         ) or return Apache2::Const::HTTP_BAD_REQUEST;
609
610         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
611     } else {
612         $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
613             $e->requestor->id,
614             {
615                 flesh => 1,
616                 flesh_fields => {
617                     au => ['settings']
618                 }
619             }
620         ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
621     }
622     my $user_setting_map = {
623         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
624             @{
625                 $ctx->{patron_recipient}
626                 ? $ctx->{patron_recipient}->settings
627                 : $ctx->{staff_recipient}->settings
628             }
629     };
630     $ctx->{user_setting_map} = $user_setting_map;
631
632     my $default_notify = $$user_setting_map{'opac.hold_notify'} || '';
633     if ($default_notify =~ /email/) {
634         $ctx->{default_email_notify} = 'checked';
635     } else {
636         $ctx->{default_email_notify} = '';
637     }
638     if ($default_notify =~ /phone/) {
639         $ctx->{default_phone_notify} = 'checked';
640     } else {
641         $ctx->{default_phone_notify} = '';
642     }
643     if ($default_notify =~ /sms/) {
644         $ctx->{default_sms_notify} = 'checked';
645     } else {
646         $ctx->{default_sms_notify} = '';
647     }
648
649     my $request_lib = $e->requestor->ws_ou;
650     my @hold_data;
651     $ctx->{hold_data} = \@hold_data;
652
653     $data_filler = sub {
654         my $hdata = shift;
655         if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
656         if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
657         if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
658         if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
659         return $hdata;
660     };
661
662     my $type_dispatch = {
663         T => sub {
664             my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
665
666             for my $id (@targets) { # force back into the correct order
667                 my ($rec) = grep {$_->id eq $id} @$recs;
668
669                 # NOTE: if tpac ever supports locked-down pickup libs,
670                 # we'll need to pass a pickup_lib param along with the 
671                 # record to filter the set of monographic parts.
672                 my $parts = $U->simplereq(
673                     'open-ils.search',
674                     'open-ils.search.biblio.record_hold_parts', 
675                     {record => $rec->id}
676                 );
677
678                 # T holds on records that have parts are OK, but if the record has 
679                 # no non-part copies, the hold will ultimately fail.  When that 
680                 # happens, require the user to select a part.
681                 my $part_required = 0;
682                 if (@$parts) {
683                     my $np_copies = $e->json_query({
684                         select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]}, 
685                         from => {acp => {acn => {}, acpm => {type => 'left'}}}, 
686                         where => {
687                             '+acp' => {deleted => 'f'},
688                             '+acn' => {deleted => 'f', record => $rec->id}, 
689                             '+acpm' => {id => undef}
690                         }
691                     });
692                     $part_required = 1 if $np_copies->[0]->{count} == 0;
693                 }
694
695                 push(@hold_data, $data_filler->({
696                     target => $rec,
697                     record => $rec,
698                     parts => $parts,
699                     part_required => $part_required
700                 }));
701             }
702         },
703         V => sub {
704             my $vols = $e->batch_retrieve_asset_call_number([
705                 \@targets, {
706                     "flesh" => 1,
707                     "flesh_fields" => {"acn" => ["record"]}
708                 }
709             ], {substream => 1});
710
711             for my $id (@targets) { 
712                 my ($vol) = grep {$_->id eq $id} @$vols;
713                 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
714             }
715         },
716         C => sub {
717             my $copies = $e->batch_retrieve_asset_copy([
718                 \@targets, {
719                     "flesh" => 2,
720                     "flesh_fields" => {
721                         "acn" => ["record"],
722                         "acp" => ["call_number"]
723                     }
724                 }
725             ], {substream => 1});
726
727             for my $id (@targets) { 
728                 my ($copy) = grep {$_->id eq $id} @$copies;
729                 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
730             }
731         },
732         I => sub {
733             my $isses = $e->batch_retrieve_serial_issuance([
734                 \@targets, {
735                     "flesh" => 2,
736                     "flesh_fields" => {
737                         "siss" => ["subscription"], "ssub" => ["record_entry"]
738                     }
739                 }
740             ], {substream => 1});
741
742             for my $id (@targets) { 
743                 my ($iss) = grep {$_->id eq $id} @$isses;
744                 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
745             }
746         }
747         # ...
748
749     }->{$ctx->{hold_type}}->();
750
751     # caller sent bad target IDs or the wrong hold type
752     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
753
754     # generate the MARC xml for each record
755     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
756
757     my $pickup_lib = $cgi->param('pickup_lib');
758     # no pickup lib means no holds placement
759     return Apache2::Const::OK unless $pickup_lib;
760
761     $ctx->{hold_attempt_made} = 1;
762
763     # Give the original CGI params back to the user in case they
764     # want to try to override something.
765     $ctx->{orig_params} = $cgi->Vars;
766     delete $ctx->{orig_params}{submit};
767     delete $ctx->{orig_params}{hold_target};
768     delete $ctx->{orig_params}{part};
769
770     my $usr = $e->requestor->id;
771
772     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
773         # find the real hold target
774
775         $usr = $U->simplereq(
776             'open-ils.actor', 
777             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
778             $e->authtoken, $cgi->param("hold_usr"));
779
780         if (defined $U->event_code($usr)) {
781             $ctx->{hold_failed} = 1;
782             $ctx->{hold_failed_event} = $usr;
783         }
784     }
785
786     # target_id is the true target_id for holds placement.  
787     # needed for attempt_hold_placement()
788     # With the exception of P-type holds, target_id == target->id.
789     $_->{target_id} = $_->{target}->id for @hold_data;
790
791     if ($ctx->{hold_type} eq 'T') {
792
793         # Much like quantum wave-particles, P-type holds pop into 
794         # and out of existence at the user's whim.  For our purposes,
795         # we treat such holds as T(itle) holds with a selected_part 
796         # designation.  When the time comes to pass the hold information 
797         # off for holds possibility testing and placement, make it look 
798         # like a real P-type hold.
799         my (@p_holds, @t_holds);
800         
801         for my $idx (0..$#parts) {
802             my $hdata = $hold_data[$idx];
803             if (my $part = $parts[$idx]) {
804                 $hdata->{target_id} = $part;
805                 $hdata->{selected_part} = $part;
806                 push(@p_holds, $hdata);
807             } else {
808                 push(@t_holds, $hdata);
809             }
810         }
811
812         $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
813         $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
814
815     } else {
816         $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
817     }
818
819     # NOTE: we are leaving the staff-placed patron barcode cookie 
820     # in place.  Otherwise, it's not possible to place more than 
821     # one hold for the patron within a staff/patron session.  This 
822     # does leave the barcode to linger longer than is ideal, but 
823     # normal staff work flow will cause the cookie to be replaced 
824     # with each new patron anyway.
825     # TODO: See about getting the staff client to clear the cookie
826
827     # return to the place_hold page so the results of the hold
828     # placement attempt can be reported to the user
829     return Apache2::Const::OK;
830 }
831
832 sub attempt_hold_placement {
833     my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
834     my $cgi = $self->cgi;
835     my $ctx = $self->ctx;
836     my $e = $self->editor;
837
838     # First see if we should warn/block for any holds that 
839     # might have locally available items.
840     for my $hdata (@hold_data) {
841         my ($local_block, $local_alert) = $self->local_avail_concern(
842             $hdata->{target_id}, $hold_type, $pickup_lib);
843     
844         if ($local_block) {
845             $hdata->{hold_failed} = 1;
846             $hdata->{hold_local_block} = 1;
847         } elsif ($local_alert) {
848             $hdata->{hold_failed} = 1;
849             $hdata->{hold_local_alert} = 1;
850         }
851     }
852
853     my $method = 'open-ils.circ.holds.test_and_create.batch';
854     $method .= '.override' if $cgi->param('override');
855
856     my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
857
858     if(@create_targets) {
859
860         my $bses = OpenSRF::AppSession->create('open-ils.circ');
861         my $breq = $bses->request( 
862             $method, 
863             $e->authtoken, 
864             $data_filler->({   patronid => $usr,
865                 pickup_lib => $pickup_lib, 
866                 hold_type => $hold_type
867             }),
868             \@create_targets
869         );
870
871         while (my $resp = $breq->recv) {
872
873             $resp = $resp->content;
874             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
875
876             if ($U->event_code($resp)) {
877                 $ctx->{general_hold_error} = $resp;
878                 last;
879             }
880
881             my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
882             my $result = $resp->{result};
883
884             if ($U->event_code($result)) {
885                 # e.g. permission denied
886                 $hdata->{hold_failed} = 1;
887                 $hdata->{hold_failed_event} = $result;
888
889             } else {
890                 
891                 if(not ref $result and $result > 0) {
892                     # successul hold returns the hold ID
893
894                     $hdata->{hold_success} = $result; 
895     
896                 } else {
897                     # hold-specific failure event 
898                     $hdata->{hold_failed} = 1;
899
900                     if (ref $result eq 'HASH') {
901                         $hdata->{hold_failed_event} = $result->{last_event};
902
903                         if ($result->{age_protected_copy}) {
904                             $hdata->{could_override} = 1;
905                             $hdata->{age_protect} = 1;
906                         } else {
907                             $hdata->{could_override} = $result->{place_unfillable};
908                         }
909                     } elsif (ref $result eq 'ARRAY') {
910                         $hdata->{hold_failed_event} = $result->[0];
911
912                         if ($result->[3]) { # age_protect_only
913                             $hdata->{could_override} = 1;
914                             $hdata->{age_protect} = 1;
915                         } else {
916                             $hdata->{could_override} = $result->[4]; # place_unfillable
917                         }
918                     }
919                 }
920             }
921         }
922
923         $bses->kill_me;
924     }
925 }
926
927 sub fetch_user_circs {
928     my $self = shift;
929     my $flesh = shift; # flesh bib data, etc.
930     my $circ_ids = shift;
931     my $limit = shift;
932     my $offset = shift;
933
934     my $e = $self->editor;
935
936     my @circ_ids;
937
938     if($circ_ids) {
939         @circ_ids = @$circ_ids;
940
941     } else {
942
943         my $query = {
944             select => {circ => ['id']},
945             from => 'circ',
946             where => {
947                 '+circ' => {
948                     usr => $e->requestor->id,
949                     checkin_time => undef,
950                     '-or' => [
951                         {stop_fines => undef},
952                         {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
953                     ],
954                 }
955             },
956             order_by => {circ => ['due_date']}
957         };
958
959         $query->{limit} = $limit if $limit;
960         $query->{offset} = $offset if $offset;
961
962         my $ids = $e->json_query($query);
963         @circ_ids = map {$_->{id}} @$ids;
964     }
965
966     return [] unless @circ_ids;
967
968     my $qflesh = {
969         flesh => 3,
970         flesh_fields => {
971             circ => ['target_copy'],
972             acp => ['call_number'],
973             acn => ['record']
974         }
975     };
976
977     $e->xact_begin;
978     my $circs = $e->search_action_circulation(
979         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
980
981     my @circs;
982     for my $circ (@$circs) {
983         push(@circs, {
984             circ => $circ, 
985             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
986                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
987                 undef  # pre-cat copy, use the dummy title/author instead
988         });
989     }
990     $e->xact_rollback;
991
992     # make sure the final list is in the correct order
993     my @sorted_circs;
994     for my $id (@circ_ids) {
995         push(
996             @sorted_circs,
997             (grep { $_->{circ}->id == $id } @circs)
998         );
999     }
1000
1001     return \@sorted_circs;
1002 }
1003
1004
1005 sub handle_circ_renew {
1006     my $self = shift;
1007     my $action = shift;
1008     my $ctx = $self->ctx;
1009
1010     my @renew_ids = $self->cgi->param('circ');
1011
1012     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1013
1014     # TODO: fire off renewal calls in batches to speed things up
1015     my @responses;
1016     for my $circ (@$circs) {
1017
1018         my $evt = $U->simplereq(
1019             'open-ils.circ', 
1020             'open-ils.circ.renew',
1021             $self->editor->authtoken,
1022             {
1023                 patron_id => $self->editor->requestor->id,
1024                 copy_id => $circ->{circ}->target_copy,
1025                 opac_renewal => 1
1026             }
1027         );
1028
1029         # TODO return these, then insert them into the circ data 
1030         # blob that is shoved into the template for each circ
1031         # so the template won't have to match them
1032         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1033     }
1034
1035     return @responses;
1036 }
1037
1038
1039 sub load_myopac_circs {
1040     my $self = shift;
1041     my $e = $self->editor;
1042     my $ctx = $self->ctx;
1043
1044     $ctx->{circs} = [];
1045     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1046     my $offset = $self->cgi->param('offset') || 0;
1047     my $action = $self->cgi->param('action') || '';
1048
1049     # perform the renewal first if necessary
1050     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1051
1052     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1053
1054     my $success_renewals = 0;
1055     my $failed_renewals = 0;
1056     for my $data (@{$ctx->{circs}}) {
1057         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1058
1059         if($resp) {
1060             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1061             $data->{renewal_response} = $evt;
1062             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1063             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1064         }
1065     }
1066
1067     $ctx->{success_renewals} = $success_renewals;
1068     $ctx->{failed_renewals} = $failed_renewals;
1069
1070     return Apache2::Const::OK;
1071 }
1072
1073 sub load_myopac_circ_history {
1074     my $self = shift;
1075     my $e = $self->editor;
1076     my $ctx = $self->ctx;
1077     my $limit = $self->cgi->param('limit') || 15;
1078     my $offset = $self->cgi->param('offset') || 0;
1079
1080     $ctx->{circ_history_limit} = $limit;
1081     $ctx->{circ_history_offset} = $offset;
1082
1083     my $circ_ids = $e->json_query({
1084         select => {
1085             au => [{
1086                 column => 'id', 
1087                 transform => 'action.usr_visible_circs', 
1088                 result_field => 'id'
1089             }]
1090         },
1091         from => 'au',
1092         where => {id => $e->requestor->id}, 
1093         limit => $limit,
1094         offset => $offset
1095     });
1096
1097     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1098     return Apache2::Const::OK;
1099 }
1100
1101 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
1102 sub load_myopac_hold_history {
1103     my $self = shift;
1104     my $e = $self->editor;
1105     my $ctx = $self->ctx;
1106     my $limit = $self->cgi->param('limit') || 15;
1107     my $offset = $self->cgi->param('offset') || 0;
1108     $ctx->{hold_history_limit} = $limit;
1109     $ctx->{hold_history_offset} = $offset;
1110
1111     my $hold_ids = $e->json_query({
1112         select => {
1113             au => [{
1114                 column => 'id', 
1115                 transform => 'action.usr_visible_holds', 
1116                 result_field => 'id'
1117             }]
1118         },
1119         from => 'au',
1120         where => {id => $e->requestor->id}, 
1121         limit => $limit,
1122         offset => $offset
1123     });
1124
1125     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
1126     return Apache2::Const::OK;
1127 }
1128
1129 sub load_myopac_payment_form {
1130     my $self = shift;
1131     my $r;
1132
1133     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1134     $r = $self->prepare_extended_user_info and return $r;
1135
1136     return Apache2::Const::OK;
1137 }
1138
1139 # TODO: add other filter options as params/configs/etc.
1140 sub load_myopac_payments {
1141     my $self = shift;
1142     my $limit = $self->cgi->param('limit') || 20;
1143     my $offset = $self->cgi->param('offset') || 0;
1144     my $e = $self->editor;
1145
1146     $self->ctx->{payment_history_limit} = $limit;
1147     $self->ctx->{payment_history_offset} = $offset;
1148
1149     my $args = {};
1150     $args->{limit} = $limit if $limit;
1151     $args->{offset} = $offset if $offset;
1152
1153     if (my $max_age = $self->ctx->{get_org_setting}->(
1154         $e->requestor->home_ou, "opac.payment_history_age_limit"
1155     )) {
1156         my $min_ts = DateTime->now(
1157             "time_zone" => DateTime::TimeZone->new("name" => "local"),
1158         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1159         
1160         $logger->info("XXX min_ts: $min_ts");
1161         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1162     }
1163
1164     $self->ctx->{payments} = $U->simplereq(
1165         'open-ils.actor',
1166         'open-ils.actor.user.payments.retrieve.atomic',
1167         $e->authtoken, $e->requestor->id, $args);
1168
1169     return Apache2::Const::OK;
1170 }
1171
1172 # 1. caches the form parameters
1173 # 2. loads the credit card payment "Processing..." page
1174 sub load_myopac_pay_init {
1175     my $self = shift;
1176     my $cache = OpenSRF::Utils::Cache->new('global');
1177
1178     my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1179
1180     if (!@payment_xacts) {
1181         # for consistency with load_myopac_payment_form() and
1182         # to preserve backwards compatibility, if no xacts are
1183         # selected, assume all (applicable) transactions are wanted.
1184         my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1185         return $stat if $stat;
1186         @payment_xacts =
1187             map { $_->{xact}->id } (
1188                 @{$self->ctx->{fines}->{circulation}}, 
1189                 @{$self->ctx->{fines}->{grocery}}
1190         );
1191     }
1192
1193     return $self->generic_redirect unless @payment_xacts;
1194
1195     my $cc_args = {"where_process" => 1};
1196
1197     $cc_args->{$_} = $self->cgi->param($_) for (qw/
1198         number cvv2 expire_year expire_month billing_first
1199         billing_last billing_address billing_city billing_state
1200         billing_zip
1201     /);
1202
1203     my $cache_args = {
1204         cc_args => $cc_args, 
1205         user => $self->ctx->{user}->id,
1206         xacts => \@payment_xacts
1207     };
1208
1209     # generate a temporary cache token and cache the form data
1210     my $token = md5_hex($$ . time() . rand());
1211     $cache->put_cache($token, $cache_args, 30);
1212
1213     $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1214
1215     # after we render the processing page, we quickly redirect to submit
1216     # the actual payment.  The refresh url contains the payment token.
1217     # It also contains the list of xact IDs, which allows us to clear the 
1218     # cache at the earliest possible time while leaving a trace of which 
1219     # transactions we were processing, so the UI can bring the user back
1220     # to the payment form w/ the same xacts if the payment fails.
1221
1222     my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1223     $refresh .= ";xact=$_" for @payment_xacts;
1224     $self->ctx->{refresh} = $refresh;
1225
1226     return Apache2::Const::OK;
1227 }
1228
1229 # retrieve the cached CC payment info and send off for processing
1230 sub load_myopac_pay {
1231     my $self = shift;
1232     my $token = $self->ctx->{page_args}->[0];
1233     return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1234
1235     my $cache = OpenSRF::Utils::Cache->new('global');
1236     my $cache_args = $cache->get_cache($token);
1237     $cache->delete_cache($token);
1238
1239     # this page is loaded immediately after the token is created.
1240     # if the cached data is not there, it's because of an invalid
1241     # token (or cache failure) and not because of a timeout.
1242     return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1243
1244     my @payment_xacts = @{$cache_args->{xacts}};
1245     my $cc_args = $cache_args->{cc_args};
1246
1247     # as an added security check, verify the user submitting 
1248     # the form is the same as the user whose data was cached
1249     return Apache2::Const::HTTP_BAD_REQUEST unless
1250         $cache_args->{user} == $self->ctx->{user}->id;
1251
1252     $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1253
1254     my $r;
1255     $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1256
1257     # balance_owed is computed specifically from the fines we're paying
1258     if ($self->ctx->{fines}->{balance_owed} <= 0) {
1259         $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1260         return Apache2::Const::HTTP_BAD_REQUEST;
1261     }
1262
1263     my $args = {
1264         "cc_args" => $cc_args,
1265         "userid" => $self->ctx->{user}->id,
1266         "payment_type" => "credit_card_payment",
1267         "payments" => $self->prepare_fines_for_payment  # should be safe after self->prepare_fines
1268     };
1269
1270     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1271         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1272     );
1273
1274     $self->ctx->{"payment_response"} = $resp;
1275
1276     unless ($resp->{"textcode"}) {
1277         $self->ctx->{printable_receipt} = $U->simplereq(
1278            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1279            $self->editor->authtoken, $resp->{payments}
1280         );
1281     }
1282
1283     return Apache2::Const::OK;
1284 }
1285
1286 sub load_myopac_receipt_print {
1287     my $self = shift;
1288
1289     $self->ctx->{printable_receipt} = $U->simplereq(
1290        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1291        $self->editor->authtoken, [$self->cgi->param("payment")]
1292     );
1293
1294     return Apache2::Const::OK;
1295 }
1296
1297 sub load_myopac_receipt_email {
1298     my $self = shift;
1299
1300     # The following ML method doesn't actually check whether the user in
1301     # question has an email address, so we do.
1302     if ($self->ctx->{user}->email) {
1303         $self->ctx->{email_receipt_result} = $U->simplereq(
1304            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1305            $self->editor->authtoken, [$self->cgi->param("payment")]
1306         );
1307     } else {
1308         $self->ctx->{email_receipt_result} =
1309             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1310     }
1311
1312     return Apache2::Const::OK;
1313 }
1314
1315 sub prepare_fines {
1316     my ($self, $limit, $offset, $id_list) = @_;
1317
1318     # XXX TODO: check for failure after various network calls
1319
1320     # It may be unclear, but this result structure lumps circulation and
1321     # reservation fines together, and keeps grocery fines separate.
1322     $self->ctx->{"fines"} = {
1323         "circulation" => [],
1324         "grocery" => [],
1325         "total_paid" => 0,
1326         "total_owed" => 0,
1327         "balance_owed" => 0
1328     };
1329
1330     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1331
1332     # TODO: This should really be a ML call, but the existing calls 
1333     # return an excessive amount of data and don't offer streaming
1334
1335     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1336
1337     my $req = $cstore->request(
1338         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1339         {
1340             usr => $self->editor->requestor->id,
1341             balance_owed => {'!=' => 0},
1342             ($id_list && @$id_list ? ("id" => $id_list) : ()),
1343         },
1344         {
1345             flesh => 4,
1346             flesh_fields => {
1347                 mobts => [qw/grocery circulation reservation/],
1348                 bresv => ['target_resource_type'],
1349                 brt => ['record'],
1350                 mg => ['billings'],
1351                 mb => ['btype'],
1352                 circ => ['target_copy'],
1353                 acp => ['call_number'],
1354                 acn => ['record']
1355             },
1356             order_by => { mobts => 'xact_start' },
1357             %paging
1358         }
1359     );
1360
1361     my @total_keys = qw/total_paid total_owed balance_owed/;
1362     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1363
1364     while(my $resp = $req->recv) {
1365         my $mobts = $resp->content;
1366         my $circ = $mobts->circulation;
1367
1368         my $last_billing;
1369         if($mobts->grocery) {
1370             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1371             $last_billing = pop(@billings);
1372         }
1373
1374         # XXX TODO confirm that the following, and the later division by 100.0
1375         # to get a floating point representation once again, is sufficiently
1376         # "money-safe" math.
1377         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1378
1379         my $marc_xml = undef;
1380         if ($mobts->xact_type eq 'reservation' and
1381             $mobts->reservation->target_resource_type->record) {
1382             $marc_xml = XML::LibXML->new->parse_string(
1383                 $mobts->reservation->target_resource_type->record->marc
1384             );
1385         } elsif ($mobts->xact_type eq 'circulation' and
1386             $circ->target_copy->call_number->id != -1) {
1387             $marc_xml = XML::LibXML->new->parse_string(
1388                 $circ->target_copy->call_number->record->marc
1389             );
1390         }
1391
1392         push(
1393             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1394             {
1395                 xact => $mobts,
1396                 last_grocery_billing => $last_billing,
1397                 marc_xml => $marc_xml
1398             } 
1399         );
1400     }
1401
1402     $cstore->kill_me;
1403
1404     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1405     return;
1406 }
1407
1408 sub prepare_fines_for_payment {
1409     # This assumes $self->prepare_fines has already been run
1410     my ($self) = @_;
1411
1412     my @results = ();
1413     if ($self->ctx->{fines}) {
1414         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1415             @{$self->ctx->{fines}->{circulation}},
1416             @{$self->ctx->{fines}->{grocery}}
1417         );
1418     }
1419
1420     return \@results;
1421 }
1422
1423 sub load_myopac_main {
1424     my $self = shift;
1425     my $limit = $self->cgi->param('limit') || 0;
1426     my $offset = $self->cgi->param('offset') || 0;
1427     $self->ctx->{search_ou} = $self->_get_search_lib();
1428
1429     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1430 }
1431
1432 sub load_myopac_update_email {
1433     my $self = shift;
1434     my $e = $self->editor;
1435     my $ctx = $self->ctx;
1436     my $email = $self->cgi->param('email') || '';
1437     my $current_pw = $self->cgi->param('current_pw') || '';
1438
1439     # needed for most up-to-date email address
1440     if (my $r = $self->prepare_extended_user_info) { return $r };
1441
1442     return Apache2::Const::OK 
1443         unless $self->cgi->request_method eq 'POST';
1444
1445     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1446         $ctx->{invalid_email} = $email;
1447         return Apache2::Const::OK;
1448     }
1449
1450     my $stat = $U->simplereq(
1451         'open-ils.actor', 
1452         'open-ils.actor.user.email.update', 
1453         $e->authtoken, $email, $current_pw);
1454
1455     if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1456         $ctx->{password_incorrect} = 1;
1457         return Apache2::Const::OK;
1458     }
1459
1460     unless ($self->cgi->param("redirect_to")) {
1461         my $url = $self->apache->unparsed_uri;
1462         $url =~ s/update_email/prefs/;
1463
1464         return $self->generic_redirect($url);
1465     }
1466
1467     return $self->generic_redirect;
1468 }
1469
1470 sub load_myopac_update_username {
1471     my $self = shift;
1472     my $e = $self->editor;
1473     my $ctx = $self->ctx;
1474     my $username = $self->cgi->param('username') || '';
1475     my $current_pw = $self->cgi->param('current_pw') || '';
1476
1477     $self->prepare_extended_user_info;
1478
1479     my $allow_change = 1;
1480     my $regex_check;
1481     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1482     if($lock_usernames == 1) {
1483         # Policy says no username changes
1484         $allow_change = 0;
1485     } else {
1486         # We want this further down.
1487         $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1488         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1489         if($username_unlimit != 1) {
1490             if(!$regex_check) {
1491                 # Default is "starts with a number"
1492                 $regex_check = '^\d+';
1493             }
1494             # You already have a username?
1495             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1496                 $allow_change = 0;
1497             }
1498         }
1499     }
1500     if(!$allow_change) {
1501         my $url = $self->apache->unparsed_uri;
1502         $url =~ s/update_username/prefs/;
1503
1504         return $self->generic_redirect($url);
1505     }
1506
1507     return Apache2::Const::OK 
1508         unless $self->cgi->request_method eq 'POST';
1509
1510     unless($username and $username !~ /\s/) { # any other username restrictions?
1511         $ctx->{invalid_username} = $username;
1512         return Apache2::Const::OK;
1513     }
1514
1515     # New username can't look like a barcode if we have a barcode regex
1516     if($regex_check and $username =~ /$regex_check/) {
1517         $ctx->{invalid_username} = $username;
1518         return Apache2::Const::OK;
1519     }
1520
1521     # New username has to look like a username if we have a username regex
1522     $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1523     if($regex_check and $username !~ /$regex_check/) {
1524         $ctx->{invalid_username} = $username;
1525         return Apache2::Const::OK;
1526     }
1527
1528     if($username ne $e->requestor->usrname) {
1529
1530         my $evt = $U->simplereq(
1531             'open-ils.actor', 
1532             'open-ils.actor.user.username.update', 
1533             $e->authtoken, $username, $current_pw);
1534
1535         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1536             $ctx->{password_incorrect} = 1;
1537             return Apache2::Const::OK;
1538         }
1539
1540         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1541             $ctx->{username_exists} = $username;
1542             return Apache2::Const::OK;
1543         }
1544     }
1545
1546     my $url = $self->apache->unparsed_uri;
1547     $url =~ s/update_username/prefs/;
1548
1549     return $self->generic_redirect($url);
1550 }
1551
1552 sub load_myopac_update_password {
1553     my $self = shift;
1554     my $e = $self->editor;
1555     my $ctx = $self->ctx;
1556
1557     return Apache2::Const::OK 
1558         unless $self->cgi->request_method eq 'POST';
1559
1560     my $current_pw = $self->cgi->param('current_pw') || '';
1561     my $new_pw = $self->cgi->param('new_pw') || '';
1562     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1563
1564     unless($new_pw eq $new_pw2) {
1565         $ctx->{password_nomatch} = 1;
1566         return Apache2::Const::OK;
1567     }
1568
1569     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1570
1571     if(!$pw_regex) {
1572         # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1573         $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1574     }
1575
1576     if($pw_regex and $new_pw !~ /$pw_regex/) {
1577         $ctx->{password_invalid} = 1;
1578         return Apache2::Const::OK;
1579     }
1580
1581     my $evt = $U->simplereq(
1582         'open-ils.actor', 
1583         'open-ils.actor.user.password.update', 
1584         $e->authtoken, $new_pw, $current_pw);
1585
1586
1587     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1588         $ctx->{password_incorrect} = 1;
1589         return Apache2::Const::OK;
1590     }
1591
1592     my $url = $self->apache->unparsed_uri;
1593     $url =~ s/update_password/prefs/;
1594
1595     return $self->generic_redirect($url);
1596 }
1597
1598 sub _update_bookbag_metadata {
1599     my ($self, $bookbag) = @_;
1600
1601     $bookbag->name($self->cgi->param("name"));
1602     $bookbag->description($self->cgi->param("description"));
1603
1604     return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1605     return 0;
1606 }
1607
1608 sub load_myopac_bookbags {
1609     my $self = shift;
1610     my $e = $self->editor;
1611     my $ctx = $self->ctx;
1612
1613     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1614     $e->xact_begin; # replication...
1615
1616     my $rv = $self->load_mylist;
1617     unless($rv eq Apache2::Const::OK) {
1618         $e->rollback;
1619         return $rv;
1620     }
1621
1622     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1623         [
1624             {owner => $e->requestor->id, btype => 'bookbag'}, {
1625                 order_by => {cbreb => 'name'},
1626                 limit => $self->cgi->param('limit') || 10,
1627                 offset => $self->cgi->param('offset') || 0
1628             }
1629         ],
1630         {substream => 1}
1631     );
1632
1633     if(!$ctx->{bookbags}) {
1634         $e->rollback;
1635         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1636     }
1637     
1638     # If the user wants a specific bookbag's items, load them.
1639     # XXX add bookbag item paging support
1640
1641     if ($self->cgi->param("id")) {
1642         my ($bookbag) =
1643             grep { $_->id eq $self->cgi->param("id") } @{$ctx->{bookbags}};
1644
1645         if (!$bookbag) {
1646             $e->rollback;
1647             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1648         }
1649
1650         if ($self->cgi->param("action") eq "editmeta") {
1651             if (!$self->_update_bookbag_metadata($bookbag))  {
1652                 $e->rollback;
1653                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1654             } else {
1655                 $e->commit;
1656                 my $url = $self->ctx->{opac_root} . '/myopac/lists?id=' .
1657                     $bookbag->id;
1658
1659                 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1660                     if ($self->cgi->param($param)) {
1661                         $url .= ";$param=" . uri_escape($self->cgi->param($param));
1662                     }
1663                 }
1664
1665                 return $self->generic_redirect($url);
1666             }
1667         }
1668
1669         my $query = $self->_prepare_bookbag_container_query(
1670             $bookbag->id, $sorter, $modifier
1671         );
1672
1673         # XXX we need to limit the number of records per bbag; use third arg
1674         # of bib_container_items_via_search() i think.
1675         my $items = $U->bib_container_items_via_search($bookbag->id, $query)
1676             or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1677
1678         my (undef, @recs) = $self->get_records_and_facets(
1679             [ map {$_->target_biblio_record_entry->id} @$items ],
1680             undef, 
1681             {flesh => '{mra}'}
1682         );
1683
1684         $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1685
1686         $bookbag->items($items);
1687     }
1688
1689     $e->rollback;
1690     return Apache2::Const::OK;
1691 }
1692
1693
1694 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1695 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1696 sub load_myopac_bookbag_update {
1697     my ($self, $action, $list_id, @hold_recs) = @_;
1698     my $e = $self->editor;
1699     my $cgi = $self->cgi;
1700
1701     # save_notes is effectively another action, but is passed in a separate
1702     # CGI parameter for what are really just layout reasons.
1703     $action = 'save_notes' if $cgi->param('save_notes');
1704     $action ||= $cgi->param('action');
1705
1706     $list_id ||= $cgi->param('list');
1707
1708     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1709     my @selected_item = $cgi->param('selected_item');
1710     my $shared = $cgi->param('shared');
1711     my $name = $cgi->param('name');
1712     my $description = $cgi->param('description');
1713     my $success = 0;
1714     my $list;
1715
1716     # This url intentionally leaves off the edit_notes parameter, but
1717     # may need to add some back in for paging.
1718
1719     my $url = "https://" . $self->apache->hostname .
1720         $self->ctx->{opac_root} . "/myopac/lists?";
1721
1722     foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1723         if ($cgi->param($param)) {
1724             $url .= "$param=" . uri_escape($cgi->param($param)) . ";";
1725         }
1726     }
1727
1728     if ($action eq 'create') {
1729         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1730         $list->name($name);
1731         $list->description($description);
1732         $list->owner($e->requestor->id);
1733         $list->btype('bookbag');
1734         $list->pub($shared ? 't' : 'f');
1735         $success = $U->simplereq('open-ils.actor', 
1736             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1737
1738     } elsif($action eq 'place_hold') {
1739
1740         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1741         unless (@hold_recs) {
1742             if (@selected_item) {
1743                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1744                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1745             }
1746         }
1747                 
1748         return Apache2::Const::OK unless @hold_recs;
1749         $logger->info("placing holds from list page on: @hold_recs");
1750
1751         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1752         $url .= ';hold_target=' . $_ for @hold_recs;
1753         foreach my $param (('loc', 'qtype', 'query')) {
1754             if ($cgi->param($param)) {
1755                 $url .= ";$param=" . uri_escape($cgi->param($param));
1756             }
1757         }
1758         return $self->generic_redirect($url);
1759
1760     } else {
1761
1762         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1763
1764         return Apache2::Const::HTTP_BAD_REQUEST unless 
1765             $list and $list->owner == $e->requestor->id;
1766     }
1767
1768     if($action eq 'delete') {
1769         $success = $U->simplereq('open-ils.actor', 
1770             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1771
1772     } elsif($action eq 'show') {
1773         unless($U->is_true($list->pub)) {
1774             $list->pub('t');
1775             $success = $U->simplereq('open-ils.actor', 
1776                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1777         }
1778
1779     } elsif($action eq 'hide') {
1780         if($U->is_true($list->pub)) {
1781             $list->pub('f');
1782             $success = $U->simplereq('open-ils.actor', 
1783                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1784         }
1785
1786     } elsif($action eq 'rename') {
1787         if($name) {
1788             $list->name($name);
1789             $success = $U->simplereq('open-ils.actor', 
1790                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1791         }
1792
1793     } elsif($action eq 'add_rec') {
1794         foreach my $add_rec (@add_rec) {
1795             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1796             $item->bucket($list_id);
1797             $item->target_biblio_record_entry($add_rec);
1798             $success = $U->simplereq('open-ils.actor', 
1799                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1800             last unless $success;
1801         }
1802
1803     } elsif($action eq 'del_item') {
1804         foreach (@selected_item) {
1805             $success = $U->simplereq(
1806                 'open-ils.actor',
1807                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1808             );
1809             last unless $success;
1810         }
1811     } elsif ($action eq 'save_notes') {
1812         $success = $self->update_bookbag_item_notes;
1813         $url .= "&id=" . uri_escape($cgi->param("id")) if $cgi->param("id");
1814     }
1815
1816     return $self->generic_redirect($url) if $success;
1817
1818     # XXX FIXME Bucket failure doesn't have a page to show the user anything
1819     # right now. User just sees a 404 currently.
1820
1821     $self->ctx->{bucket_action} = $action;
1822     $self->ctx->{bucket_action_failed} = 1;
1823     return Apache2::Const::OK;
1824 }
1825
1826 sub update_bookbag_item_notes {
1827     my ($self) = @_;
1828     my $e = $self->editor;
1829
1830     my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
1831     my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
1832
1833     # We're going to leverage an API call that's already been written to check
1834     # permissions appropriately.
1835
1836     my $a = create OpenSRF::AppSession("open-ils.actor");
1837     my $method = "open-ils.actor.container.item_note.cud";
1838
1839     for my $note_key (@note_keys) {
1840         my $note;
1841
1842         my $id = ($note_key =~ /(\d+)/)[0];
1843
1844         if (!($note =
1845             $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
1846             my $event = $e->die_event;
1847             $self->apache->log->warn(
1848                 "error retrieving cbrebin id $id, got event " .
1849                 $event->{textcode}
1850             );
1851             $a->kill_me;
1852             $self->ctx->{bucket_action_event} = $event;
1853             return;
1854         }
1855
1856         if (length($self->cgi->param($note_key))) {
1857             $note->ischanged(1);
1858             $note->note($self->cgi->param($note_key));
1859         } else {
1860             $note->isdeleted(1);
1861         }
1862
1863         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1864
1865         if (defined $U->event_code($r)) {
1866             $self->apache->log->warn(
1867                 "attempt to modify cbrebin " . $note->id .
1868                 " returned event " .  $r->{textcode}
1869             );
1870             $e->rollback;
1871             $a->kill_me;
1872             $self->ctx->{bucket_action_event} = $r;
1873             return;
1874         }
1875     }
1876
1877     for my $item_key (@item_keys) {
1878         my $id = int(($item_key =~ /(\d+)/)[0]);
1879         my $text = $self->cgi->param($item_key);
1880
1881         chomp $text;
1882         next unless length $text;
1883
1884         my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
1885         $note->isnew(1);
1886         $note->item($id);
1887         $note->note($text);
1888
1889         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1890
1891         if (defined $U->event_code($r)) {
1892             $self->apache->log->warn(
1893                 "attempt to create cbrebin for item " . $note->item .
1894                 " returned event " .  $r->{textcode}
1895             );
1896             $e->rollback;
1897             $a->kill_me;
1898             $self->ctx->{bucket_action_event} = $r;
1899             return;
1900         }
1901     }
1902
1903     $a->kill_me;
1904     return 1;   # success
1905 }
1906
1907 sub load_myopac_bookbag_print {
1908     my ($self) = @_;
1909
1910     my $id = int($self->cgi->param("list"));
1911
1912     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1913
1914     my $item_search =
1915         $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
1916
1917     my $bbag;
1918
1919     # Get the bookbag object itself, assuming we're allowed to.
1920     if ($self->editor->allowed("VIEW_CONTAINER")) {
1921
1922         $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1923     } else {
1924         my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
1925             {
1926                 "id" => $id,
1927                 "-or" => {
1928                     "owner" => $self->editor->requestor->id,
1929                     "pub" => "t"
1930                 }
1931             }
1932         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1933
1934         $bbag = pop @$bookbags;
1935     }
1936
1937     # If we have a bookbag we're allowed to look at, issue the A/T event
1938     # to get CSV, passing as a user param that search query we built before.
1939     if ($bbag) {
1940         $self->ctx->{csv} = $U->fire_object_event(
1941             undef, "container.biblio_record_entry_bucket.csv",
1942             $bbag, $self->editor->requestor->home_ou,
1943             undef, {"item_search" => $item_search}
1944         );
1945     }
1946
1947     # Create a reasonable filename and set the content disposition to
1948     # provoke browser download dialogs.
1949     (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
1950
1951     return $self->set_file_download_headers("$filename.csv");
1952 }
1953
1954 sub load_myopac_circ_history_export {
1955     my $self = shift;
1956     my $e = $self->editor;
1957     my $filename = $self->cgi->param('filename') || 'circ_history.csv';
1958
1959     my $ids = $e->json_query({
1960         select => {
1961             au => [{
1962                 column => 'id', 
1963                 transform => 'action.usr_visible_circs', 
1964                 result_field => 'id'
1965             }]
1966         },
1967         from => 'au',
1968         where => {id => $e->requestor->id} 
1969     });
1970
1971     $self->ctx->{csv} = $U->fire_object_event(
1972         undef, 
1973         'circ.format.history.csv',
1974         $e->search_action_circulation({id => [map {$_->{id}} @$ids]}, {substream =>1}),
1975         $self->editor->requestor->home_ou
1976     );
1977
1978     return $self->set_file_download_headers($filename);
1979 }
1980
1981 sub load_password_reset {
1982     my $self = shift;
1983     my $cgi = $self->cgi;
1984     my $ctx = $self->ctx;
1985     my $barcode = $cgi->param('barcode');
1986     my $username = $cgi->param('username');
1987     my $email = $cgi->param('email');
1988     my $pwd1 = $cgi->param('pwd1');
1989     my $pwd2 = $cgi->param('pwd2');
1990     my $uuid = $ctx->{page_args}->[0];
1991
1992     if ($uuid) {
1993
1994         $logger->info("patron password reset with uuid $uuid");
1995
1996         if ($pwd1 and $pwd2) {
1997
1998             if ($pwd1 eq $pwd2) {
1999
2000                 my $response = $U->simplereq(
2001                     'open-ils.actor', 
2002                     'open-ils.actor.patron.password_reset.commit',
2003                     $uuid, $pwd1);
2004
2005                 $logger->info("patron password reset response " . Dumper($response));
2006
2007                 if ($U->event_code($response)) { # non-success event
2008                     
2009                     my $code = $response->{textcode};
2010                     
2011                     if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2012                         $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2013                     }
2014
2015                     if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2016                         $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2017                     }
2018
2019                 } else { # success
2020
2021                     $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2022                 }
2023
2024             } else { # passwords not equal
2025
2026                 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2027             }
2028
2029         } else { # 2 password values needed
2030
2031             $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2032         }
2033
2034     } elsif ($barcode or $username) {
2035
2036         my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2037         push(@params, $email) if $email;
2038
2039         $U->simplereq(
2040             'open-ils.actor', 
2041             'open-ils.actor.patron.password_reset.request', @params);
2042
2043         $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2044     }
2045
2046     $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2047     return Apache2::Const::OK;
2048 }
2049
2050 1;