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