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