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