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