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;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Cache;
11 use Digest::MD5 qw(md5_hex);
13 $Data::Dumper::Indent = 0;
15 my $U = 'OpenILS::Application::AppUtils';
17 sub prepare_extended_user_info {
20 my $e = $self->editor;
22 # are we already in a transaction?
23 my $local_xact = !$e->{xact_id};
24 $e->xact_begin if $local_xact;
26 # keep the original user object so we can restore
27 # login-specific data (e.g. workstation)
28 my $usr = $self->ctx->{user};
30 $self->ctx->{user} = $self->editor->retrieve_actor_user([
31 $self->ctx->{user}->id,
35 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
41 $e->rollback if $local_xact;
43 $self->ctx->{user}->wsid($usr->wsid);
44 $self->ctx->{user}->ws_ou($usr->ws_ou);
46 # discard replaced (negative-id) addresses.
47 $self->ctx->{user}->addresses([
48 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
50 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
51 unless $self->ctx->{user};
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) = @_;
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");
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) = @_;
73 my $would_block = $self->ctx->{get_org_setting}->
74 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
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;
81 if ($would_block or $would_alert) {
83 "hold_target" => $hold_target,
84 "hold_type" => $hold_type,
85 "org_unit" => $pickup_lib
87 my $local_avail = $U->simplereq(
89 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
92 "copy availability information for " . Dumper($args) .
93 " is " . Dumper($local_avail)
95 if (%$local_avail) { # if hash not empty
96 $self->ctx->{hold_copy_available} = $local_avail;
97 return ($would_block, $would_alert);
105 # user : au object, fleshed
106 sub load_myopac_prefs {
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');
114 $self->prepare_extended_user_info;
115 my $user = $self->ctx->{user};
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;
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');
126 # Default is "starts with a number"
127 $regex_check = '^\d+';
129 # You already have a username?
130 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
131 $self->ctx->{username_change_disallowed} = 1;
136 return Apache2::Const::OK unless
137 $pending_addr or $replace_addr or $delete_pending;
139 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
142 if( $pending_addr ) { # update an existing pending address
144 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
145 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
146 $paddr->$_( $cgi->param($_) ) for @form_fields;
148 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
150 $paddr = Fieldmapper::actor::user_address->new;
152 $paddr->usr($user->id);
153 $paddr->pending('t');
154 $paddr->replaces($replace_addr);
155 $paddr->$_( $cgi->param($_) ) for @form_fields;
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);
164 my $resp = $U->simplereq(
166 'open-ils.actor.user.address.pending.cud',
167 $e->authtoken, $paddr);
169 if( $U->event_code($resp) ) {
170 $logger->error("Error updating pending address: $resp");
171 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
174 # in light of these changes, re-fetch latest data
176 $self->prepare_extended_user_info;
179 return Apache2::Const::OK;
182 sub load_myopac_prefs_notify {
184 my $e = $self->editor;
187 my $stat = $self->_load_user_with_prefs;
188 return $stat if $stat;
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';
194 $self->ctx->{opt_in_settings} = $user_prefs;
196 return Apache2::Const::OK
197 unless $self->cgi->request_method eq 'POST';
200 my $set_map = $self->ctx->{user_setting_map};
204 opac.default_sms_notify
206 my $val = $self->cgi->param($key);
207 $settings{$key}= $val unless $$set_map{$key} eq $val;
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;
214 $key = 'opac.hold_notify';
215 my @notify_methods = ();
216 if ($self->cgi->param($key . ".email") eq 'on') {
217 push @notify_methods, "email";
219 if ($self->cgi->param($key . ".phone") eq 'on') {
220 push @notify_methods, "phone";
222 if ($self->cgi->param($key . ".sms") eq 'on') {
223 push @notify_methods, "sms";
225 $val = join("|",@notify_methods);
226 $settings{$key}= $val unless $$set_map{$key} eq $val;
228 # Send the modified settings off to be saved
231 'open-ils.actor.patron.settings.update',
232 $self->editor->authtoken, undef, \%settings);
234 # re-fetch user prefs
235 $self->ctx->{updated_user_settings} = \%settings;
236 return $self->_load_user_with_prefs || Apache2::Const::OK;
239 sub fetch_optin_prefs {
241 my $e = $self->editor;
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(
249 'open-ils.actor.event_def.opt_in.settings.atomic',
250 $e->authtoken, $e->requestor->home_ou);
252 # some opt-ins are staff-only
253 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
255 # fetch user setting values for each of the opt-in settings
256 my $user_set = $U->simplereq(
258 'open-ils.actor.patron.settings.retrieve',
261 [map {$_->name} @$opt_ins]
264 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
267 sub load_myopac_messages {
269 my $e = $self->editor;
270 my $ctx = $self->ctx;
271 my $cgi = $self->cgi;
273 my $limit = $cgi->param('limit') || 20;
274 my $offset = $cgi->param('offset') || 0;
276 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
279 my $action = $cgi->param('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();
290 my $single = $cgi->param('single') || 0;
291 my $id = $cgi->param('message_id');
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;
305 # fetch all the messages
306 ($ctx->{patron_messages_count}, $messages) =
307 $self->_fetch_user_messages($pcrud, $offset, $limit);
312 foreach my $aum (@$messages) {
314 push @{ $ctx->{patron_messages} }, {
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,
324 $ctx->{patron_messages_limit} = $limit;
325 $ctx->{patron_messages_offset} = $offset;
327 return Apache2::Const::OK;
330 sub _fetch_and_mark_read_single_message {
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,
340 usr => $self->editor->requestor->id,
346 flesh_fields => { auml => ['sending_lib'] },
350 $messages->[0]->read_date('now');
352 'open-ils.pcrud.update.auml',
353 $self->editor->authtoken,
357 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
359 $self->update_dashboard_stats();
364 sub _fetch_user_messages {
370 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
372 my $all_messages = $pcrud->request(
373 'open-ils.pcrud.id_list.auml.atomic',
374 $self->editor->authtoken,
376 usr => $self->editor->requestor->id,
382 my $messages = $pcrud->request(
383 'open-ils.pcrud.search.auml.atomic',
384 $self->editor->authtoken,
386 usr => $self->editor->requestor->id,
391 flesh_fields => { auml => ['sending_lib'] },
392 order_by => { auml => 'create_date DESC' },
397 return scalar(@$all_messages), $messages;
400 sub _handle_message_action {
404 my $cgi = $self->cgi;
406 my @ids = $cgi->param('message_id');
407 return (0, 0) unless @ids;
411 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
413 my $aum = $pcrud->request(
414 'open-ils.pcrud.retrieve.auml',
415 $self->editor->authtoken,
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') {
426 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
431 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
433 $failed = scalar(@ids);
435 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
437 return ($changed, $failed);
440 sub _load_lists_and_settings {
442 my $e = $self->editor;
443 my $stat = $self->_load_user_with_prefs;
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(
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
457 # We also want a total count of the user's bookbags.
459 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
461 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
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."
469 'select' => {'cbreb' => ['name']},
471 'where' => {'id' => $exclude}
473 $r = $e->json_query($q);
474 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
482 sub update_optin_prefs {
484 my $user_prefs = shift;
485 my $e = $self->editor;
486 my @settings = $self->cgi->param('setting');
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;
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;
504 'open-ils.actor.patron.settings.update',
505 $e->authtoken, $e->requestor->id, \%newsets);
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};
516 sub _load_user_with_prefs {
518 my $stat = $self->prepare_extended_user_info('settings');
519 return $stat if $stat; # not-OK
521 $self->ctx->{user_setting_map} = {
522 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
523 @{$self->ctx->{user}->settings}
529 sub _get_bookbag_sort_params {
530 my ($self, $param_name) = @_;
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) || "";
539 $sorter =~ s/^(.*?)\.(.*)/$1/;
540 $modifier = $2 || undef;
543 return ($sorter, $modifier);
546 sub _prepare_bookbag_container_query {
547 my ($self, $container_id, $sorter, $modifier) = @_;
550 "container(bre,bookbag,%d,%s)%s%s",
551 $container_id, $self->editor->authtoken,
552 ($sorter ? " sort($sorter)" : ""),
553 ($modifier ? "#$modifier" : "")
557 sub _prepare_anonlist_sorting_query {
558 my ($self, $list, $sorter, $modifier) = @_;
561 "record_list(%s)%s%s",
563 ($sorter ? " sort($sorter)" : ""),
564 ($modifier ? "#$modifier" : "")
569 sub load_myopac_prefs_settings {
574 opac.default_search_location
575 opac.default_pickup_location
576 opac.temporary_list_no_warn
579 my $stat = $self->_load_user_with_prefs;
580 return $stat if $stat;
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');
595 $e->retrieve_config_usr_setting_type(
596 'circ.holds_behind_desk');
598 if ($U->is_true($setting->opac_visible)) {
599 push(@user_prefs, 'circ.holds_behind_desk');
600 $self->ctx->{behind_desk_supported} = 1;
604 return Apache2::Const::OK
605 unless $self->cgi->request_method eq 'POST';
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.
612 my $set_map = $self->ctx->{user_setting_map};
614 foreach my $key (@user_prefs) {
615 my $val = $self->cgi->param($key);
616 $settings{$key}= $val unless $$set_map{$key} eq $val;
619 # Used by the settings update form when warning on history delete.
620 my $clear_circ_history = 0;
621 my $clear_hold_history = 0;
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');
627 my $now = DateTime->now->strftime('%F');
629 qw/history.circ.retention_start history.hold.retention_start/) {
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};
638 next unless $$set_map{$key}; # nothing to do
640 $clear_circ_history = 1 if $key =~ /circ/;
641 $clear_hold_history = 1 if $key =~ /hold/;
643 if (!$hist_clear_confirmed) {
644 # when clearing circ history, only warn if history data exists.
646 if ($clear_circ_history) {
648 if ($self->fetch_user_circ_history(0, 1)->[0]) {
649 $hist_warning_needed = 1;
650 next; # no history updates while confirmation pending
655 my $one_hold = $e->json_query({
659 transform => 'action.usr_visible_holds',
664 where => {id => $e->requestor->id},
669 $hist_warning_needed = 1;
670 next; # no history updates while confirmation pending
675 $settings{$key} = undef;
677 if ($key eq 'history.circ.retention_start') {
678 # delete existing circulation history data.
681 'open-ils.actor.history.circ.clear',
682 $self->editor->authtoken);
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;
694 # Send the modified settings off to be saved
697 'open-ils.actor.patron.settings.update',
698 $self->editor->authtoken, undef, \%settings);
700 # re-fetch user prefs
701 $self->ctx->{updated_user_settings} = \%settings;
702 return $self->_load_user_with_prefs || Apache2::Const::OK;
705 sub load_myopac_prefs_my_lists {
710 opac.list_items_per_page
713 my $stat = $self->_load_user_with_prefs;
714 return $stat if $stat;
716 return Apache2::Const::OK
717 unless $self->cgi->request_method eq 'POST';
720 my $set_map = $self->ctx->{user_setting_map};
722 foreach my $key (@user_prefs) {
723 my $val = $self->cgi->param($key);
724 $settings{$key}= $val unless $$set_map{$key} eq $val;
727 if (keys %settings) { # we found a different setting value
728 # Send the modified settings off to be saved
731 'open-ils.actor.patron.settings.update',
732 $self->editor->authtoken, undef, \%settings);
734 # re-fetch user prefs
735 $self->ctx->{updated_user_settings} = \%settings;
736 $stat = $self->_load_user_with_prefs;
739 return $stat || Apache2::Const::OK;
742 sub fetch_user_holds {
744 my $hold_ids = shift;
745 my $ids_only = shift;
747 my $available = shift;
751 my $e = $self->editor;
752 my $all_ids; # to be used below.
755 my $circ = OpenSRF::AppSession->create('open-ils.circ');
757 $hold_ids = $circ->request(
758 'open-ils.circ.holds.id_list.retrieve.authoritative',
765 $all_ids = $hold_ids;
766 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
769 $all_ids = $hold_ids;
772 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
775 suppress_notices => 1,
776 suppress_transits => 1,
778 suppress_patron_details => 1
781 # ----------------------------------------------------------------
782 # Collect holds in batches of $batch_size for faster retrieval
786 my $mk_req_batch = sub {
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});
802 my(@collected, @holds, @ses);
805 @ses = $mk_req_batch->() if $first;
806 last if $first and not @ses;
809 while(my $blob = pop(@collected)) {
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};
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});
822 my $filter_org = $U->org_unit_ancestor_at_depth(
824 $hold->selection_depth);
826 my $filter_data = $U->simplereq(
828 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
829 $hold->target, $filter_org, [$hold->id]
832 $blob->{metarecord_filters} =
833 $filter_data->[0]->{metarecord};
834 $blob->{metarecord_selected_filters} =
835 $filter_data->[1]->{hold};
838 (undef, @data) = $self->get_records_and_facets(
839 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
843 $blob->{marc_xml} = $data[0]->{marc_xml};
848 for my $req_data (@ses) {
849 push(@collected, {hold => $req_data->{req}->gather(1)});
850 $req_data->{ses}->kill_me;
853 @ses = $mk_req_batch->();
854 last unless @collected or @ses;
858 # put the holds back into the original server sort order
860 for my $id (@$hold_ids) {
861 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
864 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids };
867 sub handle_hold_update {
870 my $hold_ids = shift;
871 my $e = $self->editor;
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/;
877 my $circ = OpenSRF::AppSession->create('open-ils.circ');
879 if($action =~ /cancel/) {
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
886 } elsif ($action =~ /activate|suspend/) {
889 for my $hold_id (@hold_ids) {
890 my $vals = {id => $hold_id};
892 if($action =~ /activate/) {
893 $vals->{frozen} = 'f';
894 $vals->{thaw_date} = undef;
896 } elsif($action =~ /suspend/) {
897 $vals->{frozen} = 't';
898 # $vals->{thaw_date} = TODO;
900 push(@$vlist, $vals);
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;
907 } elsif ($action eq 'edit') {
910 my $val = {"id" => $_};
911 $val->{"frozen"} = $self->cgi->param("frozen");
912 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
914 for my $field (qw/expire_time thaw_date/) {
915 # XXX TODO make this support other date formats, not just
917 next unless $self->cgi->param($field) =~
918 m:^(\d{2})/(\d{2})/(\d{4})$:;
919 $val->{$field} = "$3-$1-$2";
922 $val->{holdable_formats} = # no-op for non-MR holds
923 $self->compile_holdable_formats(undef, $_);
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));
941 return defined($url) ? $self->generic_redirect($url) : undef;
944 sub load_myopac_holds {
946 my $e = $self->editor;
947 my $ctx = $self->ctx;
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);
955 my $hold_handle_result;
956 $hold_handle_result = $self->handle_hold_update($action) if $action;
959 if ($self->cgi->param('sort') ne "") {
960 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
963 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
966 if($holds_object->{holds}) {
967 $ctx->{holds} = $holds_object->{holds};
969 $ctx->{holds_ids} = $holds_object->{all_ids};
970 $ctx->{holds_limit} = $limit;
971 $ctx->{holds_offset} = $offset;
973 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
978 sub load_place_hold {
980 my $ctx = $self->ctx;
981 my $gos = $ctx->{get_org_setting};
982 my $e = $self->editor;
983 my $cgi = $self->cgi;
985 $self->ctx->{page} = 'place_hold';
986 my @targets = $cgi->param('hold_target');
987 my @parts = $cgi->param('part');
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');
995 if ($cgi->param('sms_notify_checkbox')) {
996 $ctx->{sms_notify} = $cgi->param('sms_notify');
997 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1000 return $self->generic_redirect unless @targets;
1002 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1004 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1009 au => ['settings', 'card']
1012 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1013 my $user_setting_map = {
1014 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1016 $ctx->{staff_recipient}->settings
1019 $ctx->{user_setting_map} = $user_setting_map;
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';
1025 $ctx->{default_email_notify} = '';
1027 if ($default_notify =~ /phone/) {
1028 $ctx->{default_phone_notify} = 'checked';
1030 $ctx->{default_phone_notify} = '';
1032 if ($default_notify =~ /sms/) {
1033 $ctx->{default_sms_notify} = 'checked';
1035 $ctx->{default_sms_notify} = '';
1037 if ($cgi->param('hold_suspend')) {
1039 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1040 $ctx->{thaw_date} = "$3-$1-$2";
1045 # If we have a default pickup location, grab it
1046 if ($$user_setting_map{'opac.default_pickup_location'}) {
1047 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1050 my $request_lib = $e->requestor->ws_ou;
1052 $ctx->{hold_data} = \@hold_data;
1054 $data_filler = sub {
1056 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1057 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1058 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1059 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1060 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1061 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1065 my $type_dispatch = {
1067 # target metarecords
1068 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1070 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1074 for my $id (@targets) {
1075 my ($mr) = grep {$_->id eq $id} @$mrecs;
1077 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1078 my $filter_data = $U->simplereq(
1080 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1082 my $holdable_formats =
1083 $self->compile_holdable_formats($mr->id);
1085 push(@hold_data, $data_filler->({
1087 record => $mr->master_record,
1088 holdable_formats => $holdable_formats,
1089 metarecord_filters => $filter_data->{metarecord}
1094 my $recs = $e->batch_retrieve_biblio_record_entry(
1095 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1099 for my $id (@targets) { # force back into the correct order
1100 my ($rec) = grep {$_->id eq $id} @$recs;
1102 # NOTE: if tpac ever supports locked-down pickup libs,
1103 # we'll need to pass a pickup_lib param along with the
1104 # record to filter the set of monographic parts.
1105 my $parts = $U->simplereq(
1107 'open-ils.search.biblio.record_hold_parts',
1108 {record => $rec->id}
1111 # T holds on records that have parts are OK, but if the record has
1112 # no non-part copies, the hold will ultimately fail. When that
1113 # happens, require the user to select a part.
1114 my $part_required = 0;
1116 my $np_copies = $e->json_query({
1117 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1118 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1120 '+acp' => {deleted => 'f'},
1121 '+acn' => {deleted => 'f', record => $rec->id},
1122 '+acpm' => {id => undef}
1125 $part_required = 1 if $np_copies->[0]->{count} == 0;
1128 push(@hold_data, $data_filler->({
1132 part_required => $part_required
1137 my $vols = $e->batch_retrieve_asset_call_number([
1140 "flesh_fields" => {"acn" => ["record"]}
1142 ], {substream => 1});
1144 for my $id (@targets) {
1145 my ($vol) = grep {$_->id eq $id} @$vols;
1146 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1150 my $copies = $e->batch_retrieve_asset_copy([
1154 "acn" => ["record"],
1155 "acp" => ["call_number"]
1158 ], {substream => 1});
1160 for my $id (@targets) {
1161 my ($copy) = grep {$_->id eq $id} @$copies;
1162 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1166 my $isses = $e->batch_retrieve_serial_issuance([
1170 "siss" => ["subscription"], "ssub" => ["record_entry"]
1173 ], {substream => 1});
1175 for my $id (@targets) {
1176 my ($iss) = grep {$_->id eq $id} @$isses;
1177 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1182 }->{$ctx->{hold_type}}->();
1184 # caller sent bad target IDs or the wrong hold type
1185 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1187 # generate the MARC xml for each record
1188 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1190 my $pickup_lib = $cgi->param('pickup_lib');
1191 # no pickup lib means no holds placement
1192 return Apache2::Const::OK unless $pickup_lib;
1194 $ctx->{hold_attempt_made} = 1;
1196 # Give the original CGI params back to the user in case they
1197 # want to try to override something.
1198 $ctx->{orig_params} = $cgi->Vars;
1199 delete $ctx->{orig_params}{submit};
1200 delete $ctx->{orig_params}{hold_target};
1201 delete $ctx->{orig_params}{part};
1203 my $usr = $e->requestor->id;
1205 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1206 # find the real hold target
1208 $usr = $U->simplereq(
1210 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1211 $e->authtoken, $cgi->param("hold_usr"));
1213 if (defined $U->event_code($usr)) {
1214 $ctx->{hold_failed} = 1;
1215 $ctx->{hold_failed_event} = $usr;
1219 # target_id is the true target_id for holds placement.
1220 # needed for attempt_hold_placement()
1221 # With the exception of P-type holds, target_id == target->id.
1222 $_->{target_id} = $_->{target}->id for @hold_data;
1224 if ($ctx->{hold_type} eq 'T') {
1226 # Much like quantum wave-particles, P-type holds pop into
1227 # and out of existence at the user's whim. For our purposes,
1228 # we treat such holds as T(itle) holds with a selected_part
1229 # designation. When the time comes to pass the hold information
1230 # off for holds possibility testing and placement, make it look
1231 # like a real P-type hold.
1232 my (@p_holds, @t_holds);
1234 for my $idx (0..$#parts) {
1235 my $hdata = $hold_data[$idx];
1236 if (my $part = $parts[$idx]) {
1237 $hdata->{target_id} = $part;
1238 $hdata->{selected_part} = $part;
1239 push(@p_holds, $hdata);
1241 push(@t_holds, $hdata);
1245 $self->apache->log->warn("$#parts : @t_holds");
1247 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1248 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1251 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1254 # NOTE: we are leaving the staff-placed patron barcode cookie
1255 # in place. Otherwise, it's not possible to place more than
1256 # one hold for the patron within a staff/patron session. This
1257 # does leave the barcode to linger longer than is ideal, but
1258 # normal staff work flow will cause the cookie to be replaced
1259 # with each new patron anyway.
1260 # TODO: See about getting the staff client to clear the cookie
1262 # return to the place_hold page so the results of the hold
1263 # placement attempt can be reported to the user
1264 return Apache2::Const::OK;
1267 sub attempt_hold_placement {
1268 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1269 my $cgi = $self->cgi;
1270 my $ctx = $self->ctx;
1271 my $e = $self->editor;
1273 # First see if we should warn/block for any holds that
1274 # might have locally available items.
1275 for my $hdata (@hold_data) {
1276 my ($local_block, $local_alert) = $self->local_avail_concern(
1277 $hdata->{target_id}, $hold_type, $pickup_lib);
1280 $hdata->{hold_failed} = 1;
1281 $hdata->{hold_local_block} = 1;
1282 } elsif ($local_alert) {
1283 $hdata->{hold_failed} = 1;
1284 $hdata->{hold_local_alert} = 1;
1288 my $method = 'open-ils.circ.holds.test_and_create.batch';
1290 if ($cgi->param('override')) {
1291 $method .= '.override';
1293 } elsif (!$ctx->{is_staff}) {
1295 $method .= '.override' if $self->ctx->{get_org_setting}->(
1296 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1299 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1302 if(@create_targets) {
1304 # holdable formats may be different for each MR hold.
1305 # map each set to the ID of the target.
1306 my $holdable_formats = {};
1307 if ($hold_type eq 'M') {
1308 $holdable_formats->{$_->{target_id}} =
1309 $_->{holdable_formats} for @hold_data;
1312 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1313 my $breq = $bses->request(
1318 pickup_lib => $pickup_lib,
1319 hold_type => $hold_type,
1320 holdable_formats_map => $holdable_formats,
1325 while (my $resp = $breq->recv) {
1327 $resp = $resp->content;
1328 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1330 if ($U->event_code($resp)) {
1331 $ctx->{general_hold_error} = $resp;
1335 my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
1336 my $result = $resp->{result};
1338 if ($U->event_code($result)) {
1339 # e.g. permission denied
1340 $hdata->{hold_failed} = 1;
1341 $hdata->{hold_failed_event} = $result;
1345 if(not ref $result and $result > 0) {
1346 # successul hold returns the hold ID
1348 $hdata->{hold_success} = $result;
1351 # hold-specific failure event
1352 $hdata->{hold_failed} = 1;
1354 if (ref $result eq 'HASH') {
1355 $hdata->{hold_failed_event} = $result->{last_event};
1357 if ($result->{age_protected_copy}) {
1358 my %temp = %{$hdata->{hold_failed_event}};
1359 my $theTextcode = $temp{"textcode"};
1360 $theTextcode.=".override";
1361 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1362 $hdata->{age_protect} = 1;
1364 $hdata->{could_override} = $result->{place_unfillable} ||
1365 $self->test_could_override($hdata->{hold_failed_event});
1367 } elsif (ref $result eq 'ARRAY') {
1368 $hdata->{hold_failed_event} = $result->[0];
1370 if ($result->[3]) { # age_protect_only
1371 my %temp = %{$hdata->{hold_failed_event}};
1372 my $theTextcode = $temp{"textcode"};
1373 $theTextcode.=".override";
1374 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1375 $hdata->{age_protect} = 1;
1377 $hdata->{could_override} = $result->[4] || # place_unfillable
1378 $self->test_could_override($hdata->{hold_failed_event});
1389 # pull the selected formats and languages for metarecord holds
1390 # from the CGI params and map them into the JSON holdable
1391 # formats...er, format.
1392 # if no metarecord is provided, we'll pull it from the target
1393 # of the provided hold.
1394 sub compile_holdable_formats {
1395 my ($self, $mr_id, $hold_id) = @_;
1396 my $e = $self->editor;
1397 my $cgi = $self->cgi;
1399 # exit early if not needed
1401 grep /metarecord_formats_|metarecord_langs_/,
1404 # CGI params are based on the MR id, since during hold placement
1405 # we have no old ID. During hold edit, map the hold ID back to
1406 # the metarecod target.
1408 $e->retrieve_action_hold_request($hold_id)->target
1411 my $format_attr = $self->ctx->{get_cgf}->(
1412 'opac.metarecord.holds.format_attr');
1414 if (!$format_attr) {
1415 $logger->error("Missing config.global_flag: ".
1416 "opac.metarecord.holds.format_attr!");
1420 $format_attr = $format_attr->value;
1422 # during hold placement or edit submission, the user selects
1423 # which of the available formats/langs are acceptable.
1424 # Capture those here as the holdable_formats for the MR hold.
1425 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1426 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1428 # map the selected attrs into the JSON holdable_formats structure
1430 if (@selected_formats) {
1432 map { {_attr => $format_attr, _val => $_} }
1436 if (@selected_langs) {
1438 map { {_attr => 'item_lang', _val => $_} }
1443 return OpenSRF::Utils::JSON->perl2JSON($blob);
1446 sub fetch_user_circs {
1448 my $flesh = shift; # flesh bib data, etc.
1449 my $circ_ids = shift;
1453 my $e = $self->editor;
1458 @circ_ids = @$circ_ids;
1463 select => {circ => ['id']},
1467 usr => $e->requestor->id,
1468 checkin_time => undef,
1470 {stop_fines => undef},
1471 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1475 order_by => {circ => ['due_date']}
1478 $query->{limit} = $limit if $limit;
1479 $query->{offset} = $offset if $offset;
1481 my $ids = $e->json_query($query);
1482 @circ_ids = map {$_->{id}} @$ids;
1485 return [] unless @circ_ids;
1490 circ => ['target_copy'],
1491 acp => ['call_number'],
1497 my $circs = $e->search_action_circulation(
1498 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1501 for my $circ (@$circs) {
1504 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1505 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1506 undef # pre-cat copy, use the dummy title/author instead
1511 # make sure the final list is in the correct order
1513 for my $id (@circ_ids) {
1516 (grep { $_->{circ}->id == $id } @circs)
1520 return \@sorted_circs;
1524 sub handle_circ_renew {
1527 my $ctx = $self->ctx;
1529 my @renew_ids = $self->cgi->param('circ');
1531 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1533 # TODO: fire off renewal calls in batches to speed things up
1535 for my $circ (@$circs) {
1537 my $evt = $U->simplereq(
1539 'open-ils.circ.renew',
1540 $self->editor->authtoken,
1542 patron_id => $self->editor->requestor->id,
1543 copy_id => $circ->{circ}->target_copy,
1548 # TODO return these, then insert them into the circ data
1549 # blob that is shoved into the template for each circ
1550 # so the template won't have to match them
1551 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1557 sub load_myopac_circs {
1559 my $e = $self->editor;
1560 my $ctx = $self->ctx;
1563 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1564 my $offset = $self->cgi->param('offset') || 0;
1565 my $action = $self->cgi->param('action') || '';
1567 # perform the renewal first if necessary
1568 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1570 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1572 my $success_renewals = 0;
1573 my $failed_renewals = 0;
1574 for my $data (@{$ctx->{circs}}) {
1575 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1578 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1580 # extract the fail_part, if present, from the event payload;
1581 # since # the payload is an acp object in some cases,
1582 # blindly looking for a # 'fail_part' key in the template can
1584 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
1585 $evt->{payload}->{fail_part} :
1588 $data->{renewal_response} = $evt;
1589 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1590 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1594 $ctx->{success_renewals} = $success_renewals;
1595 $ctx->{failed_renewals} = $failed_renewals;
1597 return Apache2::Const::OK;
1600 sub load_myopac_circ_history {
1602 my $e = $self->editor;
1603 my $ctx = $self->ctx;
1604 my $limit = $self->cgi->param('limit') || 15;
1605 my $offset = $self->cgi->param('offset') || 0;
1606 my $action = $self->cgi->param('action') || '';
1608 my $circ_handle_result;
1609 $circ_handle_result = $self->handle_circ_update($action) if $action;
1611 $ctx->{circ_history_limit} = $limit;
1612 $ctx->{circ_history_offset} = $offset;
1614 # Defer limitation to circ_history.tt2 when sorting
1615 if ($self->cgi->param('sort')) {
1620 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
1621 return Apache2::Const::OK;
1624 # if 'flesh' is set, copy data etc. is loaded and the return value is
1625 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
1627 sub fetch_user_circ_history {
1628 my ($self, $flesh, $limit, $offset) = @_;
1629 my $e = $self->editor;
1632 $limits{offset} = $offset if defined $offset;
1633 $limits{limit} = $limit if defined $limit;
1638 auch => ['target_copy'],
1639 acp => ['call_number'],
1645 my $circs = $e->search_action_user_circ_history(
1647 {usr => $e->requestor->id},
1648 { # order newest to oldest by default
1649 order_by => {auch => 'xact_start DESC'},
1650 $flesh ? %flesh_ops : (),
1658 return $circs unless $flesh;
1662 my %unapi_cache = ();
1663 for my $circ (@$circs) {
1664 if ($circ->target_copy->call_number->id == -1) {
1667 marc_xml => undef # pre-cat copy, use the dummy title/author instead
1671 my $bre_id = $circ->target_copy->call_number->record->id;
1673 if (exists $unapi_cache{$bre_id}) {
1674 $unapi = $unapi_cache{$bre_id};
1676 my $result = $e->json_query({
1678 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
1682 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
1693 marc_xml => undef # failed, but try to go on
1702 sub handle_circ_update {
1705 my $circ_ids = shift;
1707 my $circ_ids //= [$self->cgi->param('circ_id')];
1709 if ($action =~ /delete/) {
1711 circ_ids => $circ_ids,
1716 'open-ils.actor.history.circ.clear',
1717 $self->editor->authtoken,
1725 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1726 sub load_myopac_hold_history {
1728 my $e = $self->editor;
1729 my $ctx = $self->ctx;
1730 my $limit = $self->cgi->param('limit') || 15;
1731 my $offset = $self->cgi->param('offset') || 0;
1732 $ctx->{hold_history_limit} = $limit;
1733 $ctx->{hold_history_offset} = $offset;
1735 my $hold_ids = $e->json_query({
1739 transform => 'action.usr_visible_holds',
1740 result_field => 'id'
1744 where => {id => $e->requestor->id}
1747 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1748 if($holds_object->{holds}) {
1749 $ctx->{holds} = $holds_object->{holds};
1751 $ctx->{hold_history_ids} = $holds_object->{all_ids};
1753 return Apache2::Const::OK;
1756 sub load_myopac_payment_form {
1760 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1761 $r = $self->prepare_extended_user_info and return $r;
1763 return Apache2::Const::OK;
1766 # TODO: add other filter options as params/configs/etc.
1767 sub load_myopac_payments {
1769 my $limit = $self->cgi->param('limit') || 20;
1770 my $offset = $self->cgi->param('offset') || 0;
1771 my $e = $self->editor;
1773 $self->ctx->{payment_history_limit} = $limit;
1774 $self->ctx->{payment_history_offset} = $offset;
1777 $args->{limit} = $limit if $limit;
1778 $args->{offset} = $offset if $offset;
1780 if (my $max_age = $self->ctx->{get_org_setting}->(
1781 $e->requestor->home_ou, "opac.payment_history_age_limit"
1783 my $min_ts = DateTime->now(
1784 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1785 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1787 $logger->info("XXX min_ts: $min_ts");
1788 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1791 $self->ctx->{payments} = $U->simplereq(
1793 'open-ils.actor.user.payments.retrieve.atomic',
1794 $e->authtoken, $e->requestor->id, $args);
1796 return Apache2::Const::OK;
1799 # 1. caches the form parameters
1800 # 2. loads the credit card payment "Processing..." page
1801 sub load_myopac_pay_init {
1803 my $cache = OpenSRF::Utils::Cache->new('global');
1805 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1807 if (!@payment_xacts) {
1808 # for consistency with load_myopac_payment_form() and
1809 # to preserve backwards compatibility, if no xacts are
1810 # selected, assume all (applicable) transactions are wanted.
1811 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1812 return $stat if $stat;
1814 map { $_->{xact}->id } (
1815 @{$self->ctx->{fines}->{circulation}},
1816 @{$self->ctx->{fines}->{grocery}}
1820 return $self->generic_redirect unless @payment_xacts;
1822 my $cc_args = {"where_process" => 1};
1824 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1825 number cvv2 expire_year expire_month billing_first
1826 billing_last billing_address billing_city billing_state
1827 billing_zip stripe_token
1831 cc_args => $cc_args,
1832 user => $self->ctx->{user}->id,
1833 xacts => \@payment_xacts
1836 # generate a temporary cache token and cache the form data
1837 my $token = md5_hex($$ . time() . rand());
1838 $cache->put_cache($token, $cache_args, 30);
1840 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1842 # after we render the processing page, we quickly redirect to submit
1843 # the actual payment. The refresh url contains the payment token.
1844 # It also contains the list of xact IDs, which allows us to clear the
1845 # cache at the earliest possible time while leaving a trace of which
1846 # transactions we were processing, so the UI can bring the user back
1847 # to the payment form w/ the same xacts if the payment fails.
1849 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1850 $refresh .= ";xact=$_" for @payment_xacts;
1851 $self->ctx->{refresh} = $refresh;
1853 return Apache2::Const::OK;
1856 # retrieve the cached CC payment info and send off for processing
1857 sub load_myopac_pay {
1859 my $token = $self->ctx->{page_args}->[0];
1860 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1862 my $cache = OpenSRF::Utils::Cache->new('global');
1863 my $cache_args = $cache->get_cache($token);
1864 $cache->delete_cache($token);
1866 # this page is loaded immediately after the token is created.
1867 # if the cached data is not there, it's because of an invalid
1868 # token (or cache failure) and not because of a timeout.
1869 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1871 my @payment_xacts = @{$cache_args->{xacts}};
1872 my $cc_args = $cache_args->{cc_args};
1874 # as an added security check, verify the user submitting
1875 # the form is the same as the user whose data was cached
1876 return Apache2::Const::HTTP_BAD_REQUEST unless
1877 $cache_args->{user} == $self->ctx->{user}->id;
1879 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1882 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1884 # balance_owed is computed specifically from the fines we're paying
1885 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1886 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1887 return Apache2::Const::HTTP_BAD_REQUEST;
1891 "cc_args" => $cc_args,
1892 "userid" => $self->ctx->{user}->id,
1893 "payment_type" => "credit_card_payment",
1894 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1897 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1898 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1901 $self->ctx->{"payment_response"} = $resp;
1903 unless ($resp->{"textcode"}) {
1904 $self->ctx->{printable_receipt} = $U->simplereq(
1905 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1906 $self->editor->authtoken, $resp->{payments}
1910 return Apache2::Const::OK;
1913 sub load_myopac_receipt_print {
1916 $self->ctx->{printable_receipt} = $U->simplereq(
1917 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1918 $self->editor->authtoken, [$self->cgi->param("payment")]
1921 return Apache2::Const::OK;
1924 sub load_myopac_receipt_email {
1927 # The following ML method doesn't actually check whether the user in
1928 # question has an email address, so we do.
1929 if ($self->ctx->{user}->email) {
1930 $self->ctx->{email_receipt_result} = $U->simplereq(
1931 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1932 $self->editor->authtoken, [$self->cgi->param("payment")]
1935 $self->ctx->{email_receipt_result} =
1936 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1939 return Apache2::Const::OK;
1943 my ($self, $limit, $offset, $id_list) = @_;
1945 # XXX TODO: check for failure after various network calls
1947 # It may be unclear, but this result structure lumps circulation and
1948 # reservation fines together, and keeps grocery fines separate.
1949 $self->ctx->{"fines"} = {
1950 "circulation" => [],
1957 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1959 # TODO: This should really be a ML call, but the existing calls
1960 # return an excessive amount of data and don't offer streaming
1962 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1964 my $req = $cstore->request(
1965 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1967 usr => $self->editor->requestor->id,
1968 balance_owed => {'!=' => 0},
1969 ($id_list && @$id_list ? ("id" => $id_list) : ()),
1974 mobts => [qw/grocery circulation reservation/],
1975 bresv => ['target_resource_type'],
1979 circ => ['target_copy'],
1980 acp => ['call_number'],
1983 order_by => { mobts => 'xact_start' },
1988 # Collect $$ amounts from each transaction for summing below.
1989 my (@paid_amounts, @owed_amounts, @balance_amounts);
1991 while(my $resp = $req->recv) {
1992 my $mobts = $resp->content;
1993 my $circ = $mobts->circulation;
1996 if($mobts->grocery) {
1997 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1998 $last_billing = pop(@billings);
2001 push(@paid_amounts, $mobts->total_paid);
2002 push(@owed_amounts, $mobts->total_owed);
2003 push(@balance_amounts, $mobts->balance_owed);
2005 my $marc_xml = undef;
2006 if ($mobts->xact_type eq 'reservation' and
2007 $mobts->reservation->target_resource_type->record) {
2008 $marc_xml = XML::LibXML->new->parse_string(
2009 $mobts->reservation->target_resource_type->record->marc
2011 } elsif ($mobts->xact_type eq 'circulation' and
2012 $circ->target_copy->call_number->id != -1) {
2013 $marc_xml = XML::LibXML->new->parse_string(
2014 $circ->target_copy->call_number->record->marc
2019 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2022 last_grocery_billing => $last_billing,
2023 marc_xml => $marc_xml
2030 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2031 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2032 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2037 sub prepare_fines_for_payment {
2038 # This assumes $self->prepare_fines has already been run
2042 if ($self->ctx->{fines}) {
2043 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2044 @{$self->ctx->{fines}->{circulation}},
2045 @{$self->ctx->{fines}->{grocery}}
2052 sub load_myopac_main {
2054 my $limit = $self->cgi->param('limit') || 0;
2055 my $offset = $self->cgi->param('offset') || 0;
2056 $self->ctx->{search_ou} = $self->_get_search_lib();
2057 $self->ctx->{user}->notes(
2058 $self->editor->search_actor_usr_note({
2059 usr => $self->ctx->{user}->id,
2063 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2066 sub load_myopac_update_email {
2068 my $e = $self->editor;
2069 my $ctx = $self->ctx;
2070 my $email = $self->cgi->param('email') || '';
2071 my $current_pw = $self->cgi->param('current_pw') || '';
2073 # needed for most up-to-date email address
2074 if (my $r = $self->prepare_extended_user_info) { return $r };
2076 return Apache2::Const::OK
2077 unless $self->cgi->request_method eq 'POST';
2079 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2080 $ctx->{invalid_email} = $email;
2081 return Apache2::Const::OK;
2084 my $stat = $U->simplereq(
2086 'open-ils.actor.user.email.update',
2087 $e->authtoken, $email, $current_pw);
2089 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2090 $ctx->{password_incorrect} = 1;
2091 return Apache2::Const::OK;
2094 unless ($self->cgi->param("redirect_to")) {
2095 my $url = $self->apache->unparsed_uri;
2096 $url =~ s/update_email/prefs/;
2098 return $self->generic_redirect($url);
2101 return $self->generic_redirect;
2104 sub load_myopac_update_username {
2106 my $e = $self->editor;
2107 my $ctx = $self->ctx;
2108 my $username = $self->cgi->param('username') || '';
2109 my $current_pw = $self->cgi->param('current_pw') || '';
2111 $self->prepare_extended_user_info;
2113 my $allow_change = 1;
2115 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2116 if(defined($lock_usernames) and $lock_usernames == 1) {
2117 # Policy says no username changes
2120 # We want this further down.
2121 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2122 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2123 if(!$username_unlimit) {
2125 # Default is "starts with a number"
2126 $regex_check = '^\d+';
2128 # You already have a username?
2129 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2134 if(!$allow_change) {
2135 my $url = $self->apache->unparsed_uri;
2136 $url =~ s/update_username/prefs/;
2138 return $self->generic_redirect($url);
2141 return Apache2::Const::OK
2142 unless $self->cgi->request_method eq 'POST';
2144 unless($username and $username !~ /\s/) { # any other username restrictions?
2145 $ctx->{invalid_username} = $username;
2146 return Apache2::Const::OK;
2149 # New username can't look like a barcode if we have a barcode regex
2150 if($regex_check and $username =~ /$regex_check/) {
2151 $ctx->{invalid_username} = $username;
2152 return Apache2::Const::OK;
2155 # New username has to look like a username if we have a username regex
2156 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2157 if($regex_check and $username !~ /$regex_check/) {
2158 $ctx->{invalid_username} = $username;
2159 return Apache2::Const::OK;
2162 if($username ne $e->requestor->usrname) {
2164 my $evt = $U->simplereq(
2166 'open-ils.actor.user.username.update',
2167 $e->authtoken, $username, $current_pw);
2169 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2170 $ctx->{password_incorrect} = 1;
2171 return Apache2::Const::OK;
2174 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2175 $ctx->{username_exists} = $username;
2176 return Apache2::Const::OK;
2180 my $url = $self->apache->unparsed_uri;
2181 $url =~ s/update_username/prefs/;
2183 return $self->generic_redirect($url);
2186 sub load_myopac_update_password {
2188 my $e = $self->editor;
2189 my $ctx = $self->ctx;
2191 return Apache2::Const::OK
2192 unless $self->cgi->request_method eq 'POST';
2194 my $current_pw = $self->cgi->param('current_pw') || '';
2195 my $new_pw = $self->cgi->param('new_pw') || '';
2196 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2198 unless($new_pw eq $new_pw2) {
2199 $ctx->{password_nomatch} = 1;
2200 return Apache2::Const::OK;
2203 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2206 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2207 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2210 if($pw_regex and $new_pw !~ /$pw_regex/) {
2211 $ctx->{password_invalid} = 1;
2212 return Apache2::Const::OK;
2215 my $evt = $U->simplereq(
2217 'open-ils.actor.user.password.update',
2218 $e->authtoken, $new_pw, $current_pw);
2221 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2222 $ctx->{password_incorrect} = 1;
2223 return Apache2::Const::OK;
2226 my $url = $self->apache->unparsed_uri;
2227 $url =~ s/update_password/prefs/;
2229 return $self->generic_redirect($url);
2232 sub _update_bookbag_metadata {
2233 my ($self, $bookbag) = @_;
2235 $bookbag->name($self->cgi->param("name"));
2236 $bookbag->description($self->cgi->param("description"));
2238 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2242 sub _get_lists_per_page {
2245 if($self->editor->requestor) {
2246 $self->timelog("Checking for opac.lists_per_page preference");
2247 # See if the user has a lists per page preference
2248 my $ipp = $self->editor->search_actor_user_setting({
2249 usr => $self->editor->requestor->id,
2250 name => 'opac.lists_per_page'
2252 $self->timelog("Got opac.lists_per_page preference");
2253 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2255 return 10; # default
2258 sub _get_items_per_page {
2261 if($self->editor->requestor) {
2262 $self->timelog("Checking for opac.list_items_per_page preference");
2263 # See if the user has a list items per page preference
2264 my $ipp = $self->editor->search_actor_user_setting({
2265 usr => $self->editor->requestor->id,
2266 name => 'opac.list_items_per_page'
2268 $self->timelog("Got opac.list_items_per_page preference");
2269 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2271 return 10; # default
2274 sub load_myopac_bookbags {
2276 my $e = $self->editor;
2277 my $ctx = $self->ctx;
2278 my $limit = $self->_get_lists_per_page || 10;
2279 my $offset = $self->cgi->param('offset') || 0;
2281 $ctx->{bookbags_limit} = $limit;
2282 $ctx->{bookbags_offset} = $offset;
2284 # for list item pagination
2285 my $item_limit = $self->_get_items_per_page;
2286 my $item_page = $self->cgi->param('item_page') || 1;
2287 my $item_offset = ($item_page - 1) * $item_limit;
2288 $ctx->{bookbags_item_page} = $item_page;
2290 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2291 $e->xact_begin; # replication...
2293 my $rv = $self->load_mylist;
2294 unless($rv eq Apache2::Const::OK) {
2299 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2301 {owner => $e->requestor->id, btype => 'bookbag'}, {
2302 order_by => {cbreb => 'name'},
2310 if(!$ctx->{bookbags}) {
2312 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2315 # We load the user prefs to get their default bookbag.
2316 $self->_load_user_with_prefs;
2318 # We also want a total count of the user's bookbags.
2320 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2322 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2324 my $r = $e->json_query($q);
2325 $ctx->{bookbag_count} = $r->[0]->{'count'};
2327 # If the user wants a specific bookbag's items, load them.
2329 if ($self->cgi->param("bbid")) {
2331 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2334 my $query = $self->_prepare_bookbag_container_query(
2335 $bookbag->id, $sorter, $modifier
2338 # Calculate total count of the items in selected bookbag.
2339 # This total includes record entries that have no assets available.
2340 my $bb_search_results = $U->simplereq(
2341 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2342 {"limit" => 1, "offset" => 0}, $query
2343 ); # we only need the count, so do the actual search with limit=1
2345 if ($bb_search_results) {
2346 $ctx->{bb_item_count} = $bb_search_results->{count};
2348 $logger->warn("search failed in load_myopac_bookbags()");
2349 $ctx->{bb_item_count} = 0; # fallback value
2352 #calculate page count
2353 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2355 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2356 if (!$self->_update_bookbag_metadata($bookbag)) {
2358 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2361 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2364 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2365 if ($self->cgi->param($param)) {
2366 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
2370 return $self->generic_redirect($url);
2374 # we're done with our CStoreEditor. Rollback here so
2375 # later calls don't cause a timeout, resulting in a
2376 # transaction rollback under the covers.
2380 # For list items pagination
2382 "limit" => $item_limit,
2383 "offset" => $item_offset
2386 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2387 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2389 # capture pref_ou for callnumber filter/display
2390 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2392 # search for local callnumbers for display
2393 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2395 my (undef, @recs) = $self->get_records_and_facets(
2396 [ map {$_->target_biblio_record_entry->id} @$items ],
2399 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2401 site => $ctx->{get_aou}->($focus_ou)->shortname,
2402 pref_lib => $ctx->{pref_ou}
2406 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2408 $bookbag->items($items);
2412 # If we have add_rec, we got here from the "Add to new list"
2413 # or "See all" popmenu items.
2414 if (my $add_rec = $self->cgi->param('add_rec')) {
2415 $self->ctx->{add_rec} = $add_rec;
2416 # But not in the staff client, 'cause that breaks things.
2417 unless ($self->ctx->{is_staff}) {
2418 # allow caller to provide the where_from in cases where
2419 # the referer is an intermediate error page
2420 if ($self->cgi->param('where_from')) {
2421 $self->ctx->{where_from} = $self->cgi->param('where_from');
2423 $self->ctx->{where_from} = $self->ctx->{referer};
2424 if ( my $anchor = $self->cgi->param('anchor') ) {
2425 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2431 # this rollback may be a dupe, but that's OK because
2432 # cstoreditor ignores dupe rollbacks
2435 return Apache2::Const::OK;
2439 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
2440 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2441 sub load_myopac_bookbag_update {
2442 my ($self, $action, $list_id, @hold_recs) = @_;
2443 my $e = $self->editor;
2444 my $cgi = $self->cgi;
2446 # save_notes is effectively another action, but is passed in a separate
2447 # CGI parameter for what are really just layout reasons.
2448 $action = 'save_notes' if $cgi->param('save_notes');
2449 $action ||= $cgi->param('action');
2451 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2453 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2454 my @selected_item = $cgi->param('selected_item');
2455 my $shared = $cgi->param('shared');
2456 my $name = $cgi->param('name');
2457 my $description = $cgi->param('description');
2461 # This url intentionally leaves off the edit_notes parameter, but
2462 # may need to add some back in for paging.
2464 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2465 $self->ctx->{opac_root} . "/myopac/lists?";
2467 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2468 if ($cgi->param($param)) {
2469 $url .= "$param=" . uri_escape_utf8($cgi->param($param)) . ";";
2473 if ($action eq 'create') {
2476 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2478 $list->description($description);
2479 $list->owner($e->requestor->id);
2480 $list->btype('bookbag');
2481 $list->pub($shared ? 't' : 'f');
2482 $success = $U->simplereq('open-ils.actor',
2483 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2484 if (ref($success) ne 'HASH' && scalar @add_rec) {
2485 $list_id = (ref($success)) ? $success->id : $success;
2486 foreach my $add_rec (@add_rec) {
2487 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2488 $item->bucket($list_id);
2489 $item->target_biblio_record_entry($add_rec);
2490 $success = $U->simplereq('open-ils.actor',
2491 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2492 last unless $success;
2495 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
2498 $self->ctx->{bucket_failure_noname} = 1;
2501 } elsif($action eq 'place_hold') {
2503 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
2504 unless (@hold_recs) {
2505 if (@selected_item) {
2506 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
2507 @hold_recs = map { $_->target_biblio_record_entry } @$items;
2511 return Apache2::Const::OK unless @hold_recs;
2512 $logger->info("placing holds from list page on: @hold_recs");
2514 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
2515 $url .= ';hold_target=' . $_ for @hold_recs;
2516 foreach my $param (('loc', 'qtype', 'query')) {
2517 if ($cgi->param($param)) {
2518 $url .= ";$param=" . uri_escape_utf8($cgi->param($param));
2521 return $self->generic_redirect($url);
2525 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
2527 return Apache2::Const::HTTP_BAD_REQUEST unless
2528 $list and $list->owner == $e->requestor->id;
2531 if($action eq 'delete') {
2532 $success = $U->simplereq('open-ils.actor',
2533 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
2535 # We check to see if we're deleting the user's default list.
2536 $self->_load_user_with_prefs;
2537 my $settings_map = $self->ctx->{user_setting_map};
2538 if ($$settings_map{'opac.default_list'} == $list_id) {
2539 # We unset the user's opac.default_list setting.
2540 $success = $U->simplereq(
2542 'open-ils.actor.patron.settings.update',
2545 { 'opac.default_list' => 0 }
2549 } elsif($action eq 'show') {
2550 unless($U->is_true($list->pub)) {
2552 $success = $U->simplereq('open-ils.actor',
2553 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2556 } elsif($action eq 'hide') {
2557 if($U->is_true($list->pub)) {
2559 $success = $U->simplereq('open-ils.actor',
2560 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2563 } elsif($action eq 'rename') {
2566 $success = $U->simplereq('open-ils.actor',
2567 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2570 } elsif($action eq 'add_rec') {
2571 foreach my $add_rec (@add_rec) {
2572 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2573 $item->bucket($list_id);
2574 $item->target_biblio_record_entry($add_rec);
2575 $success = $U->simplereq('open-ils.actor',
2576 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2577 last unless $success;
2579 # Redirect back where we came from if we have an anchor parameter:
2580 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
2581 $url = $self->ctx->{referer};
2582 $url =~ s/#.*|$/#$anchor/;
2583 } elsif ($cgi->param('where_from')) {
2584 # Or, if we have a "where_from" parameter.
2585 $url = $cgi->param('where_from');
2587 } elsif ($action eq 'del_item') {
2588 foreach (@selected_item) {
2589 $success = $U->simplereq(
2591 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
2593 last unless $success;
2595 } elsif ($action eq 'save_notes') {
2596 $success = $self->update_bookbag_item_notes;
2597 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
2598 } elsif ($action eq 'make_default') {
2599 $success = $U->simplereq(
2601 'open-ils.actor.patron.settings.update',
2604 { 'opac.default_list' => $list_id }
2606 } elsif ($action eq 'remove_default') {
2607 $success = $U->simplereq(
2609 'open-ils.actor.patron.settings.update',
2612 { 'opac.default_list' => 0 }
2616 return $self->generic_redirect($url) if $success;
2618 $self->ctx->{where_from} = $cgi->param('where_from');
2619 $self->ctx->{bucket_action} = $action;
2620 $self->ctx->{bucket_action_failed} = 1;
2621 return Apache2::Const::OK;
2624 sub update_bookbag_item_notes {
2626 my $e = $self->editor;
2628 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2629 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2631 # We're going to leverage an API call that's already been written to check
2632 # permissions appropriately.
2634 my $a = create OpenSRF::AppSession("open-ils.actor");
2635 my $method = "open-ils.actor.container.item_note.cud";
2637 for my $note_key (@note_keys) {
2640 my $id = ($note_key =~ /(\d+)/)[0];
2643 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2644 my $event = $e->die_event;
2645 $self->apache->log->warn(
2646 "error retrieving cbrebin id $id, got event " .
2650 $self->ctx->{bucket_action_event} = $event;
2654 if (length($self->cgi->param($note_key))) {
2655 $note->ischanged(1);
2656 $note->note($self->cgi->param($note_key));
2658 $note->isdeleted(1);
2661 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2663 if (defined $U->event_code($r)) {
2664 $self->apache->log->warn(
2665 "attempt to modify cbrebin " . $note->id .
2666 " returned event " . $r->{textcode}
2670 $self->ctx->{bucket_action_event} = $r;
2675 for my $item_key (@item_keys) {
2676 my $id = int(($item_key =~ /(\d+)/)[0]);
2677 my $text = $self->cgi->param($item_key);
2680 next unless length $text;
2682 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2687 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2689 if (defined $U->event_code($r)) {
2690 $self->apache->log->warn(
2691 "attempt to create cbrebin for item " . $note->item .
2692 " returned event " . $r->{textcode}
2696 $self->ctx->{bucket_action_event} = $r;
2705 sub load_myopac_bookbag_print {
2708 my $id = int($self->cgi->param("list"));
2710 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2713 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2717 # Get the bookbag object itself, assuming we're allowed to.
2718 if ($self->editor->allowed("VIEW_CONTAINER")) {
2720 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2722 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2726 "owner" => $self->editor->requestor->id,
2730 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2732 $bbag = pop @$bookbags;
2735 # If we have a bookbag we're allowed to look at, issue the A/T event
2736 # to get CSV, passing as a user param that search query we built before.
2738 $self->ctx->{csv} = $U->fire_object_event(
2739 undef, "container.biblio_record_entry_bucket.csv",
2740 $bbag, $self->editor->requestor->home_ou,
2741 undef, {"item_search" => $item_search}
2745 # Create a reasonable filename and set the content disposition to
2746 # provoke browser download dialogs.
2747 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2749 return $self->set_file_download_headers("$filename.csv");
2752 sub load_myopac_circ_history_export {
2754 my $e = $self->editor;
2755 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2757 my $circs = $self->fetch_user_circ_history(1);
2759 $self->ctx->{csv}->{circs} = $circs;
2760 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
2764 sub load_password_reset {
2766 my $cgi = $self->cgi;
2767 my $ctx = $self->ctx;
2768 my $barcode = $cgi->param('barcode');
2769 my $username = $cgi->param('username');
2770 my $email = $cgi->param('email');
2771 my $pwd1 = $cgi->param('pwd1');
2772 my $pwd2 = $cgi->param('pwd2');
2773 my $uuid = $ctx->{page_args}->[0];
2777 $logger->info("patron password reset with uuid $uuid");
2779 if ($pwd1 and $pwd2) {
2781 if ($pwd1 eq $pwd2) {
2783 my $response = $U->simplereq(
2785 'open-ils.actor.patron.password_reset.commit',
2788 $logger->info("patron password reset response " . Dumper($response));
2790 if ($U->event_code($response)) { # non-success event
2792 my $code = $response->{textcode};
2794 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2795 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2798 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2799 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2804 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2807 } else { # passwords not equal
2809 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2812 } else { # 2 password values needed
2814 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2817 } elsif ($barcode or $username) {
2819 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2820 push(@params, $email) if $email;
2824 'open-ils.actor.patron.password_reset.request', @params);
2826 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2829 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2830 return Apache2::Const::OK;