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