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 use DateTime::Format::ISO8601;
16 my $U = 'OpenILS::Application::AppUtils';
18 sub prepare_extended_user_info {
21 my $e = $self->editor;
23 # are we already in a transaction?
24 my $local_xact = !$e->{xact_id};
25 $e->xact_begin if $local_xact;
27 # keep the original user object so we can restore
28 # login-specific data (e.g. workstation)
29 my $usr = $self->ctx->{user};
31 $self->ctx->{user} = $self->editor->retrieve_actor_user([
32 $self->ctx->{user}->id,
36 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
42 $e->rollback if $local_xact;
44 $self->ctx->{user}->wsid($usr->wsid);
45 $self->ctx->{user}->ws_ou($usr->ws_ou);
47 # discard replaced (negative-id) addresses.
48 $self->ctx->{user}->addresses([
49 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
51 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
52 unless $self->ctx->{user};
57 # Given an event returned by a failed attempt to create a hold, do we have
58 # permission to override? XXX Should the permission check be scoped to a
59 # given org_unit context?
60 sub test_could_override {
61 my ($self, $event) = @_;
63 return 0 unless $event;
64 return 1 if $self->editor->allowed($event->{textcode} . ".override");
65 return 1 if $event->{"fail_part"} and
66 $self->editor->allowed($event->{"fail_part"} . ".override");
70 # Find out whether we care that local copies are available
71 sub local_avail_concern {
72 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
74 my $would_block = $self->ctx->{get_org_setting}->
75 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
77 $self->ctx->{get_org_setting}->
78 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
79 not $self->cgi->param("override")
80 ) unless $would_block;
82 if ($would_block or $would_alert) {
84 "hold_target" => $hold_target,
85 "hold_type" => $hold_type,
86 "org_unit" => $pickup_lib
88 my $local_avail = $U->simplereq(
90 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
93 "copy availability information for " . Dumper($args) .
94 " is " . Dumper($local_avail)
96 if (%$local_avail) { # if hash not empty
97 $self->ctx->{hold_copy_available} = $local_avail;
98 return ($would_block, $would_alert);
106 # user : au object, fleshed
107 sub load_myopac_prefs {
109 my $cgi = $self->cgi;
110 my $e = $self->editor;
111 my $pending_addr = $cgi->param('pending_addr');
112 my $replace_addr = $cgi->param('replace_addr');
113 my $delete_pending = $cgi->param('delete_pending');
115 $self->prepare_extended_user_info;
116 my $user = $self->ctx->{user};
118 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
119 if(defined($lock_usernames) and $lock_usernames == 1) {
120 # Policy says no username changes
121 $self->ctx->{username_change_disallowed} = 1;
123 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
124 if(!$username_unlimit) {
125 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
127 # Default is "starts with a number"
128 $regex_check = '^\d+';
130 # You already have a username?
131 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
132 $self->ctx->{username_change_disallowed} = 1;
137 return Apache2::Const::OK unless
138 $pending_addr or $replace_addr or $delete_pending;
140 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
143 if( $pending_addr ) { # update an existing pending address
145 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
146 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
147 $paddr->$_( $cgi->param($_) ) for @form_fields;
149 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
151 $paddr = Fieldmapper::actor::user_address->new;
153 $paddr->usr($user->id);
154 $paddr->pending('t');
155 $paddr->replaces($replace_addr);
156 $paddr->$_( $cgi->param($_) ) for @form_fields;
158 } elsif( $delete_pending ) {
159 $paddr = $e->retrieve_actor_user_address($delete_pending);
160 return Apache2::Const::HTTP_BAD_REQUEST unless
161 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
162 $paddr->isdeleted(1);
165 my $resp = $U->simplereq(
167 'open-ils.actor.user.address.pending.cud',
168 $e->authtoken, $paddr);
170 if( $U->event_code($resp) ) {
171 $logger->error("Error updating pending address: $resp");
172 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
175 # in light of these changes, re-fetch latest data
177 $self->prepare_extended_user_info;
180 return Apache2::Const::OK;
183 sub load_myopac_prefs_notify {
185 my $e = $self->editor;
188 my $stat = $self->_load_user_with_prefs;
189 return $stat if $stat;
191 my $user_prefs = $self->fetch_optin_prefs;
192 $user_prefs = $self->update_optin_prefs($user_prefs)
193 if $self->cgi->request_method eq 'POST';
195 $self->ctx->{opt_in_settings} = $user_prefs;
197 return Apache2::Const::OK
198 unless $self->cgi->request_method eq 'POST';
201 my $set_map = $self->ctx->{user_setting_map};
205 opac.default_sms_notify
207 my $val = $self->cgi->param($key);
208 $settings{$key}= $val unless $$set_map{$key} eq $val;
211 my $key = 'opac.default_sms_carrier';
212 my $val = $self->cgi->param('sms_carrier');
213 $settings{$key}= $val unless $$set_map{$key} eq $val;
215 $key = 'opac.hold_notify';
216 my @notify_methods = ();
217 if ($self->cgi->param($key . ".email") eq 'on') {
218 push @notify_methods, "email";
220 if ($self->cgi->param($key . ".phone") eq 'on') {
221 push @notify_methods, "phone";
223 if ($self->cgi->param($key . ".sms") eq 'on') {
224 push @notify_methods, "sms";
226 $val = join("|",@notify_methods);
227 $settings{$key}= $val unless $$set_map{$key} eq $val;
229 # Send the modified settings off to be saved
232 'open-ils.actor.patron.settings.update',
233 $self->editor->authtoken, undef, \%settings);
235 # re-fetch user prefs
236 $self->ctx->{updated_user_settings} = \%settings;
237 return $self->_load_user_with_prefs || Apache2::Const::OK;
240 sub fetch_optin_prefs {
242 my $e = $self->editor;
244 # fetch all of the opt-in settings the user has access to
245 # XXX: user's should in theory have options to opt-in to notices
246 # for remote locations, but that opens the door for a large
247 # set of generally un-used opt-ins.. needs discussion
248 my $opt_ins = $U->simplereq(
250 'open-ils.actor.event_def.opt_in.settings.atomic',
251 $e->authtoken, $e->requestor->home_ou);
253 # some opt-ins are staff-only
254 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
256 # fetch user setting values for each of the opt-in settings
257 my $user_set = $U->simplereq(
259 'open-ils.actor.patron.settings.retrieve',
262 [map {$_->name} @$opt_ins]
265 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
268 sub load_myopac_messages {
270 my $e = $self->editor;
271 my $ctx = $self->ctx;
272 my $cgi = $self->cgi;
274 my $limit = $cgi->param('limit') || 20;
275 my $offset = $cgi->param('offset') || 0;
277 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
280 my $action = $cgi->param('action') || '';
282 my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
283 if ($changed > 0 || $failed > 0) {
284 $ctx->{message_update_action} = $action;
285 $ctx->{message_update_changed} = $changed;
286 $ctx->{message_update_failed} = $failed;
287 $self->update_dashboard_stats();
291 my $single = $cgi->param('single') || 0;
292 my $id = $cgi->param('message_id');
296 if (!$action && $single && $id) {
297 $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
298 if (scalar(@$messages) == 1) {
299 $ctx->{display_single_message} = 1;
300 $ctx->{patron_message_id} = $id;
306 # fetch all the messages
307 ($ctx->{patron_messages_count}, $messages) =
308 $self->_fetch_user_messages($pcrud, $offset, $limit);
313 foreach my $aum (@$messages) {
315 push @{ $ctx->{patron_messages} }, {
317 title => $aum->title,
318 message => $aum->message,
319 create_date => $aum->create_date,
320 is_read => defined($aum->read_date) ? 1 : 0,
321 library => $aum->sending_lib->name,
325 $ctx->{patron_messages_limit} = $limit;
326 $ctx->{patron_messages_offset} = $offset;
328 return Apache2::Const::OK;
331 sub _fetch_and_mark_read_single_message {
336 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
337 my $messages = $pcrud->request(
338 'open-ils.pcrud.search.auml.atomic',
339 $self->editor->authtoken,
341 usr => $self->editor->requestor->id,
347 flesh_fields => { auml => ['sending_lib'] },
351 $messages->[0]->read_date('now');
353 'open-ils.pcrud.update.auml',
354 $self->editor->authtoken,
358 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
360 $self->update_dashboard_stats();
365 sub _fetch_user_messages {
371 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
373 my $all_messages = $pcrud->request(
374 'open-ils.pcrud.id_list.auml.atomic',
375 $self->editor->authtoken,
377 usr => $self->editor->requestor->id,
383 my $messages = $pcrud->request(
384 'open-ils.pcrud.search.auml.atomic',
385 $self->editor->authtoken,
387 usr => $self->editor->requestor->id,
392 flesh_fields => { auml => ['sending_lib'] },
393 order_by => { auml => 'create_date DESC' },
398 return scalar(@$all_messages), $messages;
401 sub _handle_message_action {
405 my $cgi = $self->cgi;
407 my @ids = $cgi->param('message_id');
408 return (0, 0) unless @ids;
412 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
414 my $aum = $pcrud->request(
415 'open-ils.pcrud.retrieve.auml',
416 $self->editor->authtoken,
420 if ($action eq 'mark_read') {
421 $aum->read_date('now');
422 } elsif ($action eq 'mark_unread') {
423 $aum->clear_read_date();
424 } elsif ($action eq 'mark_deleted') {
427 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
432 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
434 $failed = scalar(@ids);
436 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
438 return ($changed, $failed);
441 sub _load_lists_and_settings {
443 my $e = $self->editor;
444 my $stat = $self->_load_user_with_prefs;
447 my $setting_map = $self->ctx->{user_setting_map};
448 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
449 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
451 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
452 order_by => {cbreb => 'name'},
453 limit => $self->cgi->param('limit') || 10,
454 offset => $self->cgi->param('offset') || 0
458 # We also want a total count of the user's bookbags.
460 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
462 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
464 my $r = $e->json_query($q);
465 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
466 # Someone has requested that we use the default list's name
467 # rather than "Default List."
470 'select' => {'cbreb' => ['name']},
472 'where' => {'id' => $exclude}
474 $r = $e->json_query($q);
475 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
483 sub update_optin_prefs {
485 my $user_prefs = shift;
486 my $e = $self->editor;
487 my @settings = $self->cgi->param('setting');
490 # apply now-true settings
491 for my $applied (@settings) {
492 # see if setting is already applied to this user
493 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
494 $newsets{$applied} = OpenSRF::Utils::JSON->true;
497 # remove now-false settings
498 for my $pref (grep { $_->{value} } @$user_prefs) {
499 $newsets{$pref->{cust}->name} = undef
500 unless grep { $_ eq $pref->{cust}->name } @settings;
505 'open-ils.actor.patron.settings.update',
506 $e->authtoken, $e->requestor->id, \%newsets);
508 # update the local prefs to match reality
509 for my $pref (@$user_prefs) {
510 $pref->{value} = $newsets{$pref->{cust}->name}
511 if exists $newsets{$pref->{cust}->name};
517 sub _load_user_with_prefs {
519 my $stat = $self->prepare_extended_user_info('settings');
520 return $stat if $stat; # not-OK
522 $self->ctx->{user_setting_map} = {
523 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
524 @{$self->ctx->{user}->settings}
530 sub _get_bookbag_sort_params {
531 my ($self, $param_name) = @_;
533 # The interface that feeds this cgi parameter will provide a single
534 # argument for a QP sort filter, and potentially a modifier after a period.
535 # In practice this means the "sort" parameter will be something like
536 # "titlesort" or "authorsort.descending".
537 my $sorter = $self->cgi->param($param_name) || "";
540 $sorter =~ s/^(.*?)\.(.*)/$1/;
541 $modifier = $2 || undef;
544 return ($sorter, $modifier);
547 sub _prepare_bookbag_container_query {
548 my ($self, $container_id, $sorter, $modifier) = @_;
551 "container(bre,bookbag,%d,%s)%s%s",
552 $container_id, $self->editor->authtoken,
553 ($sorter ? " sort($sorter)" : ""),
554 ($modifier ? "#$modifier" : "")
558 sub _prepare_anonlist_sorting_query {
559 my ($self, $list, $sorter, $modifier) = @_;
562 "record_list(%s)%s%s",
564 ($sorter ? " sort($sorter)" : ""),
565 ($modifier ? "#$modifier" : "")
570 sub load_myopac_prefs_settings {
575 opac.default_search_location
576 opac.default_pickup_location
577 opac.temporary_list_no_warn
580 my $stat = $self->_load_user_with_prefs;
581 return $stat if $stat;
583 # if behind-desk holds are supported and the user
584 # setting which controls the value is opac-visible,
585 # add the setting to the list of settings to manage.
586 # note: this logic may need to be changed later to
587 # check whether behind-the-desk holds are supported
588 # anywhere the patron may select as a pickup lib.
589 my $e = $self->editor;
590 my $bdous = $self->ctx->{get_org_setting}->(
591 $e->requestor->home_ou,
592 'circ.holds.behind_desk_pickup_supported');
596 $e->retrieve_config_usr_setting_type(
597 'circ.holds_behind_desk');
599 if ($U->is_true($setting->opac_visible)) {
600 push(@user_prefs, 'circ.holds_behind_desk');
601 $self->ctx->{behind_desk_supported} = 1;
605 return Apache2::Const::OK
606 unless $self->cgi->request_method eq 'POST';
608 # some setting values from the form don't match the
609 # required value/format for the db, so they have to be
610 # individually translated.
613 my $set_map = $self->ctx->{user_setting_map};
615 foreach my $key (@user_prefs) {
616 my $val = $self->cgi->param($key);
617 $settings{$key}= $val unless $$set_map{$key} eq $val;
620 # Used by the settings update form when warning on history delete.
621 my $clear_circ_history = 0;
622 my $clear_hold_history = 0;
624 # true if we need to show the warning on next page load.
625 my $hist_warning_needed = 0;
626 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
628 my $now = DateTime->now->strftime('%F');
630 qw/history.circ.retention_start history.hold.retention_start/) {
632 my $val = $self->cgi->param($key);
633 if($val and $val eq 'on') {
634 # Set the start time to 'now' unless a start time already exists for the user
635 $settings{$key} = $now unless $$set_map{$key};
639 next unless $$set_map{$key}; # nothing to do
641 $clear_circ_history = 1 if $key =~ /circ/;
642 $clear_hold_history = 1 if $key =~ /hold/;
644 if (!$hist_clear_confirmed) {
645 # when clearing circ history, only warn if history data exists.
647 if ($clear_circ_history) {
649 if ($self->fetch_user_circ_history(0, 1)->[0]) {
650 $hist_warning_needed = 1;
651 next; # no history updates while confirmation pending
656 my $one_hold = $e->json_query({
660 transform => 'action.usr_visible_holds',
665 where => {id => $e->requestor->id},
670 $hist_warning_needed = 1;
671 next; # no history updates while confirmation pending
676 $settings{$key} = undef;
678 if ($key eq 'history.circ.retention_start') {
679 # delete existing circulation history data.
682 'open-ils.actor.history.circ.clear',
683 $self->editor->authtoken);
688 # Warn patrons before clearing circ/hold history
689 if ($hist_warning_needed) {
690 $self->ctx->{clear_circ_history} = $clear_circ_history;
691 $self->ctx->{clear_hold_history} = $clear_hold_history;
692 $self->ctx->{confirm_history_delete} = 1;
695 # Send the modified settings off to be saved
698 'open-ils.actor.patron.settings.update',
699 $self->editor->authtoken, undef, \%settings);
701 # re-fetch user prefs
702 $self->ctx->{updated_user_settings} = \%settings;
703 return $self->_load_user_with_prefs || Apache2::Const::OK;
706 sub load_myopac_prefs_my_lists {
711 opac.list_items_per_page
714 my $stat = $self->_load_user_with_prefs;
715 return $stat if $stat;
717 return Apache2::Const::OK
718 unless $self->cgi->request_method eq 'POST';
721 my $set_map = $self->ctx->{user_setting_map};
723 foreach my $key (@user_prefs) {
724 my $val = $self->cgi->param($key);
725 $settings{$key}= $val unless $$set_map{$key} eq $val;
728 if (keys %settings) { # we found a different setting value
729 # Send the modified settings off to be saved
732 'open-ils.actor.patron.settings.update',
733 $self->editor->authtoken, undef, \%settings);
735 # re-fetch user prefs
736 $self->ctx->{updated_user_settings} = \%settings;
737 $stat = $self->_load_user_with_prefs;
740 return $stat || Apache2::Const::OK;
743 sub fetch_user_holds {
745 my $hold_ids = shift;
746 my $ids_only = shift;
748 my $available = shift;
752 my $e = $self->editor;
753 my $all_ids; # to be used below.
756 my $circ = OpenSRF::AppSession->create('open-ils.circ');
758 $hold_ids = $circ->request(
759 'open-ils.circ.holds.id_list.retrieve.authoritative',
766 $all_ids = $hold_ids;
767 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
770 $all_ids = $hold_ids;
773 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
776 suppress_notices => 1,
777 suppress_transits => 1,
779 suppress_patron_details => 1
782 # ----------------------------------------------------------------
783 # Collect holds in batches of $batch_size for faster retrieval
787 my $mk_req_batch = sub {
789 my $top_idx = $batch_idx + $batch_size;
790 while($batch_idx < $top_idx) {
791 my $hold_id = $hold_ids->[$batch_idx++];
792 last unless $hold_id;
793 my $ses = OpenSRF::AppSession->create('open-ils.circ');
794 my $req = $ses->request(
795 'open-ils.circ.hold.details.retrieve',
796 $e->authtoken, $hold_id, $args);
797 push(@ses, {ses => $ses, req => $req});
803 my(@collected, @holds, @ses);
806 @ses = $mk_req_batch->() if $first;
807 last if $first and not @ses;
810 while(my $blob = pop(@collected)) {
813 # in the holds edit UI, we need to know what formats and
814 # languages the user selected for this hold, plus what
815 # formats/langs are available on the MR as a whole.
816 if ($blob->{hold}{hold}->hold_type eq 'M') {
817 my $hold = $blob->{hold}->{hold};
819 # for MR, fetch the combined MR unapi blob
820 (undef, @data) = $self->get_records_and_facets(
821 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
823 my $filter_org = $U->org_unit_ancestor_at_depth(
825 $hold->selection_depth);
827 my $filter_data = $U->simplereq(
829 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
830 $hold->target, $filter_org, [$hold->id]
833 $blob->{metarecord_filters} =
834 $filter_data->[0]->{metarecord};
835 $blob->{metarecord_selected_filters} =
836 $filter_data->[1]->{hold};
839 (undef, @data) = $self->get_records_and_facets(
840 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
844 $blob->{marc_xml} = $data[0]->{marc_xml};
849 for my $req_data (@ses) {
850 push(@collected, {hold => $req_data->{req}->gather(1)});
851 $req_data->{ses}->kill_me;
854 @ses = $mk_req_batch->();
855 last unless @collected or @ses;
859 # put the holds back into the original server sort order
861 for my $id (@$hold_ids) {
862 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
865 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids };
868 sub handle_hold_update {
871 my $hold_ids = shift;
872 my $e = $self->editor;
875 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
876 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
878 my $circ = OpenSRF::AppSession->create('open-ils.circ');
880 if($action =~ /cancel/) {
882 for my $hold_id (@hold_ids) {
883 my $resp = $circ->request(
884 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
887 } elsif ($action =~ /activate|suspend/) {
890 for my $hold_id (@hold_ids) {
891 my $vals = {id => $hold_id};
893 if($action =~ /activate/) {
894 $vals->{frozen} = 'f';
895 $vals->{thaw_date} = undef;
897 } elsif($action =~ /suspend/) {
898 $vals->{frozen} = 't';
899 # $vals->{thaw_date} = TODO;
901 push(@$vlist, $vals);
904 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
905 $self->ctx->{hold_suspend_post_capture} = 1 if
906 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
908 } elsif ($action eq 'edit') {
911 my $val = {"id" => $_};
912 $val->{"frozen"} = $self->cgi->param("frozen");
913 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
915 for my $field (qw/expire_time thaw_date/) {
916 # XXX TODO make this support other date formats, not just
918 next unless $self->cgi->param($field) =~
919 m:^(\d{2})/(\d{2})/(\d{4})$:;
920 $val->{$field} = "$3-$1-$2";
923 $val->{holdable_formats} = # no-op for non-MR holds
924 $self->compile_holdable_formats(undef, $_);
930 'open-ils.circ.hold.update.batch.atomic',
931 $e->authtoken, undef, \@vals
932 )->gather(1); # LFW XXX test for failure
933 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
934 foreach my $param (('loc', 'qtype', 'query')) {
935 if ($self->cgi->param($param)) {
936 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
942 return defined($url) ? $self->generic_redirect($url) : undef;
945 sub load_myopac_holds {
947 my $e = $self->editor;
948 my $ctx = $self->ctx;
950 my $limit = $self->cgi->param('limit') || 15;
951 my $offset = $self->cgi->param('offset') || 0;
952 my $action = $self->cgi->param('action') || '';
953 my $hold_id = $self->cgi->param('id');
954 my $available = int($self->cgi->param('available') || 0);
956 my $hold_handle_result;
957 $hold_handle_result = $self->handle_hold_update($action) if $action;
960 if ($self->cgi->param('sort') ne "") {
961 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
964 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
967 if($holds_object->{holds}) {
968 $ctx->{holds} = $holds_object->{holds};
970 $ctx->{holds_ids} = $holds_object->{all_ids};
971 $ctx->{holds_limit} = $limit;
972 $ctx->{holds_offset} = $offset;
974 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
979 sub load_place_hold {
981 my $ctx = $self->ctx;
982 my $gos = $ctx->{get_org_setting};
983 my $e = $self->editor;
984 my $cgi = $self->cgi;
986 $self->ctx->{page} = 'place_hold';
987 my @targets = $cgi->param('hold_target');
988 my @parts = $cgi->param('part');
990 $ctx->{hold_type} = $cgi->param('hold_type');
991 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
992 $ctx->{email_notify} = $cgi->param('email_notify');
993 if ($cgi->param('phone_notify_checkbox')) {
994 $ctx->{phone_notify} = $cgi->param('phone_notify');
996 if ($cgi->param('sms_notify_checkbox')) {
997 $ctx->{sms_notify} = $cgi->param('sms_notify');
998 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1001 return $self->generic_redirect unless @targets;
1003 # Check for multiple hold placement via the num_copies widget.
1004 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1005 if ($num_copies > 1) {
1006 # Only if we have 1 hold target and no parts.
1007 if (scalar(@targets) == 1 && !$parts[0]) {
1008 # Also, only for M and T holds.
1009 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1010 # Add the extra holds to @targets. NOTE: We start with
1011 # 1 and go to < $num_copies to account for the
1013 for (my $i = 1; $i < $num_copies; $i++) {
1014 push(@targets, $targets[0]);
1020 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1022 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1027 au => ['settings', 'card']
1030 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1031 my $user_setting_map = {
1032 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1034 $ctx->{staff_recipient}->settings
1037 $ctx->{user_setting_map} = $user_setting_map;
1039 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1040 if ($default_notify =~ /email/) {
1041 $ctx->{default_email_notify} = 'checked';
1043 $ctx->{default_email_notify} = '';
1045 if ($default_notify =~ /phone/) {
1046 $ctx->{default_phone_notify} = 'checked';
1048 $ctx->{default_phone_notify} = '';
1050 if ($default_notify =~ /sms/) {
1051 $ctx->{default_sms_notify} = 'checked';
1053 $ctx->{default_sms_notify} = '';
1055 if ($cgi->param('hold_suspend')) {
1057 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1058 # We should use a date input type on the forms once it is supported by Firefox.
1059 # I didn't do that now because it is not available in a general release.
1060 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1062 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1063 $ctx->{thaw_date} = $dt->ymd;
1066 $logger->warn("ignoring invalid thaw_date when placing hold request");
1072 # If we have a default pickup location, grab it
1073 if ($$user_setting_map{'opac.default_pickup_location'}) {
1074 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1077 my $request_lib = $e->requestor->ws_ou;
1079 $ctx->{hold_data} = \@hold_data;
1081 $data_filler = sub {
1083 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1084 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1085 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1086 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1087 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1088 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1092 my $type_dispatch = {
1094 # target metarecords
1095 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1097 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1101 for my $id (@targets) {
1102 my ($mr) = grep {$_->id eq $id} @$mrecs;
1104 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1105 my $filter_data = $U->simplereq(
1107 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1109 my $holdable_formats =
1110 $self->compile_holdable_formats($mr->id);
1112 push(@hold_data, $data_filler->({
1114 record => $mr->master_record,
1115 holdable_formats => $holdable_formats,
1116 metarecord_filters => $filter_data->{metarecord}
1121 my $recs = $e->batch_retrieve_biblio_record_entry(
1122 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1126 for my $id (@targets) { # force back into the correct order
1127 my ($rec) = grep {$_->id eq $id} @$recs;
1129 # NOTE: if tpac ever supports locked-down pickup libs,
1130 # we'll need to pass a pickup_lib param along with the
1131 # record to filter the set of monographic parts.
1132 my $parts = $U->simplereq(
1134 'open-ils.search.biblio.record_hold_parts',
1135 {record => $rec->id}
1138 # T holds on records that have parts are OK, but if the record has
1139 # no non-part copies, the hold will ultimately fail. When that
1140 # happens, require the user to select a part.
1141 my $part_required = 0;
1143 my $np_copies = $e->json_query({
1144 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1145 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1147 '+acp' => {deleted => 'f'},
1148 '+acn' => {deleted => 'f', record => $rec->id},
1149 '+acpm' => {id => undef}
1152 $part_required = 1 if $np_copies->[0]->{count} == 0;
1155 push(@hold_data, $data_filler->({
1159 part_required => $part_required
1164 my $vols = $e->batch_retrieve_asset_call_number([
1167 "flesh_fields" => {"acn" => ["record"]}
1169 ], {substream => 1});
1171 for my $id (@targets) {
1172 my ($vol) = grep {$_->id eq $id} @$vols;
1173 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1177 my $copies = $e->batch_retrieve_asset_copy([
1181 "acn" => ["record"],
1182 "acp" => ["call_number"]
1185 ], {substream => 1});
1187 for my $id (@targets) {
1188 my ($copy) = grep {$_->id eq $id} @$copies;
1189 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1193 my $isses = $e->batch_retrieve_serial_issuance([
1197 "siss" => ["subscription"], "ssub" => ["record_entry"]
1200 ], {substream => 1});
1202 for my $id (@targets) {
1203 my ($iss) = grep {$_->id eq $id} @$isses;
1204 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1209 }->{$ctx->{hold_type}}->();
1211 # caller sent bad target IDs or the wrong hold type
1212 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1214 # generate the MARC xml for each record
1215 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1217 my $pickup_lib = $cgi->param('pickup_lib');
1218 # no pickup lib means no holds placement
1219 return Apache2::Const::OK unless $pickup_lib;
1221 $ctx->{hold_attempt_made} = 1;
1223 # Give the original CGI params back to the user in case they
1224 # want to try to override something.
1225 $ctx->{orig_params} = $cgi->Vars;
1226 delete $ctx->{orig_params}{submit};
1227 delete $ctx->{orig_params}{hold_target};
1228 delete $ctx->{orig_params}{part};
1230 my $usr = $e->requestor->id;
1232 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1233 # find the real hold target
1235 $usr = $U->simplereq(
1237 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1238 $e->authtoken, $cgi->param("hold_usr"));
1240 if (defined $U->event_code($usr)) {
1241 $ctx->{hold_failed} = 1;
1242 $ctx->{hold_failed_event} = $usr;
1246 # target_id is the true target_id for holds placement.
1247 # needed for attempt_hold_placement()
1248 # With the exception of P-type holds, target_id == target->id.
1249 $_->{target_id} = $_->{target}->id for @hold_data;
1251 if ($ctx->{hold_type} eq 'T') {
1253 # Much like quantum wave-particles, P-type holds pop into
1254 # and out of existence at the user's whim. For our purposes,
1255 # we treat such holds as T(itle) holds with a selected_part
1256 # designation. When the time comes to pass the hold information
1257 # off for holds possibility testing and placement, make it look
1258 # like a real P-type hold.
1259 my (@p_holds, @t_holds);
1261 # Now that we have the num_copies field for mutliple title and
1262 # metarecord hold placement, the number of holds and parts
1263 # arrays can get out of sync. We only want to parse out parts
1264 # if the numbers are equal.
1265 if ($#hold_data == $#parts) {
1266 for my $idx (0..$#parts) {
1267 my $hdata = $hold_data[$idx];
1268 if (my $part = $parts[$idx]) {
1269 $hdata->{target_id} = $part;
1270 $hdata->{selected_part} = $part;
1271 push(@p_holds, $hdata);
1273 push(@t_holds, $hdata);
1277 @t_holds = @hold_data;
1280 $self->apache->log->warn("$#parts : @t_holds");
1282 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1283 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1286 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1289 # NOTE: we are leaving the staff-placed patron barcode cookie
1290 # in place. Otherwise, it's not possible to place more than
1291 # one hold for the patron within a staff/patron session. This
1292 # does leave the barcode to linger longer than is ideal, but
1293 # normal staff work flow will cause the cookie to be replaced
1294 # with each new patron anyway.
1295 # TODO: See about getting the staff client to clear the cookie
1297 # return to the place_hold page so the results of the hold
1298 # placement attempt can be reported to the user
1299 return Apache2::Const::OK;
1302 sub attempt_hold_placement {
1303 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1304 my $cgi = $self->cgi;
1305 my $ctx = $self->ctx;
1306 my $e = $self->editor;
1308 # First see if we should warn/block for any holds that
1309 # might have locally available items.
1310 for my $hdata (@hold_data) {
1311 my ($local_block, $local_alert) = $self->local_avail_concern(
1312 $hdata->{target_id}, $hold_type, $pickup_lib);
1315 $hdata->{hold_failed} = 1;
1316 $hdata->{hold_local_block} = 1;
1317 } elsif ($local_alert) {
1318 $hdata->{hold_failed} = 1;
1319 $hdata->{hold_local_alert} = 1;
1323 my $method = 'open-ils.circ.holds.test_and_create.batch';
1325 if ($cgi->param('override')) {
1326 $method .= '.override';
1328 } elsif (!$ctx->{is_staff}) {
1330 $method .= '.override' if $self->ctx->{get_org_setting}->(
1331 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1334 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1337 if(@create_targets) {
1339 # holdable formats may be different for each MR hold.
1340 # map each set to the ID of the target.
1341 my $holdable_formats = {};
1342 if ($hold_type eq 'M') {
1343 $holdable_formats->{$_->{target_id}} =
1344 $_->{holdable_formats} for @hold_data;
1347 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1348 my $breq = $bses->request(
1353 pickup_lib => $pickup_lib,
1354 hold_type => $hold_type,
1355 holdable_formats_map => $holdable_formats,
1360 while (my $resp = $breq->recv) {
1362 $resp = $resp->content;
1363 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1365 if ($U->event_code($resp)) {
1366 $ctx->{general_hold_error} = $resp;
1370 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1371 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1372 my $result = $resp->{result};
1374 if ($U->event_code($result)) {
1375 # e.g. permission denied
1376 $hdata->{hold_failed} = 1;
1377 $hdata->{hold_failed_event} = $result;
1381 if(not ref $result and $result > 0) {
1382 # successul hold returns the hold ID
1384 $hdata->{hold_success} = $result;
1387 # hold-specific failure event
1388 $hdata->{hold_failed} = 1;
1390 if (ref $result eq 'HASH') {
1391 $hdata->{hold_failed_event} = $result->{last_event};
1393 if ($result->{age_protected_copy}) {
1394 my %temp = %{$hdata->{hold_failed_event}};
1395 my $theTextcode = $temp{"textcode"};
1396 $theTextcode.=".override";
1397 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1398 $hdata->{age_protect} = 1;
1400 $hdata->{could_override} = $result->{place_unfillable} ||
1401 $self->test_could_override($hdata->{hold_failed_event});
1403 } elsif (ref $result eq 'ARRAY') {
1404 $hdata->{hold_failed_event} = $result->[0];
1406 if ($result->[3]) { # age_protect_only
1407 my %temp = %{$hdata->{hold_failed_event}};
1408 my $theTextcode = $temp{"textcode"};
1409 $theTextcode.=".override";
1410 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1411 $hdata->{age_protect} = 1;
1413 $hdata->{could_override} = $result->[4] || # place_unfillable
1414 $self->test_could_override($hdata->{hold_failed_event});
1425 # pull the selected formats and languages for metarecord holds
1426 # from the CGI params and map them into the JSON holdable
1427 # formats...er, format.
1428 # if no metarecord is provided, we'll pull it from the target
1429 # of the provided hold.
1430 sub compile_holdable_formats {
1431 my ($self, $mr_id, $hold_id) = @_;
1432 my $e = $self->editor;
1433 my $cgi = $self->cgi;
1435 # exit early if not needed
1437 grep /metarecord_formats_|metarecord_langs_/,
1440 # CGI params are based on the MR id, since during hold placement
1441 # we have no old ID. During hold edit, map the hold ID back to
1442 # the metarecod target.
1444 $e->retrieve_action_hold_request($hold_id)->target
1447 my $format_attr = $self->ctx->{get_cgf}->(
1448 'opac.metarecord.holds.format_attr');
1450 if (!$format_attr) {
1451 $logger->error("Missing config.global_flag: ".
1452 "opac.metarecord.holds.format_attr!");
1456 $format_attr = $format_attr->value;
1458 # during hold placement or edit submission, the user selects
1459 # which of the available formats/langs are acceptable.
1460 # Capture those here as the holdable_formats for the MR hold.
1461 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1462 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1464 # map the selected attrs into the JSON holdable_formats structure
1466 if (@selected_formats) {
1468 map { {_attr => $format_attr, _val => $_} }
1472 if (@selected_langs) {
1474 map { {_attr => 'item_lang', _val => $_} }
1479 return OpenSRF::Utils::JSON->perl2JSON($blob);
1482 sub fetch_user_circs {
1484 my $flesh = shift; # flesh bib data, etc.
1485 my $circ_ids = shift;
1489 my $e = $self->editor;
1494 @circ_ids = @$circ_ids;
1499 select => {circ => ['id']},
1503 usr => $e->requestor->id,
1504 checkin_time => undef,
1506 {stop_fines => undef},
1507 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1511 order_by => {circ => ['due_date']}
1514 $query->{limit} = $limit if $limit;
1515 $query->{offset} = $offset if $offset;
1517 my $ids = $e->json_query($query);
1518 @circ_ids = map {$_->{id}} @$ids;
1521 return [] unless @circ_ids;
1526 circ => ['target_copy'],
1527 acp => ['call_number'],
1533 my $circs = $e->search_action_circulation(
1534 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1537 for my $circ (@$circs) {
1540 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1541 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1542 undef # pre-cat copy, use the dummy title/author instead
1547 # make sure the final list is in the correct order
1549 for my $id (@circ_ids) {
1552 (grep { $_->{circ}->id == $id } @circs)
1556 return \@sorted_circs;
1560 sub handle_circ_renew {
1563 my $ctx = $self->ctx;
1565 my @renew_ids = $self->cgi->param('circ');
1567 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1569 # TODO: fire off renewal calls in batches to speed things up
1571 for my $circ (@$circs) {
1573 my $evt = $U->simplereq(
1575 'open-ils.circ.renew',
1576 $self->editor->authtoken,
1578 patron_id => $self->editor->requestor->id,
1579 copy_id => $circ->{circ}->target_copy,
1584 # TODO return these, then insert them into the circ data
1585 # blob that is shoved into the template for each circ
1586 # so the template won't have to match them
1587 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1593 sub load_myopac_circs {
1595 my $e = $self->editor;
1596 my $ctx = $self->ctx;
1599 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1600 my $offset = $self->cgi->param('offset') || 0;
1601 my $action = $self->cgi->param('action') || '';
1603 # perform the renewal first if necessary
1604 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1606 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1608 my $success_renewals = 0;
1609 my $failed_renewals = 0;
1610 for my $data (@{$ctx->{circs}}) {
1611 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1614 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1616 # extract the fail_part, if present, from the event payload;
1617 # since # the payload is an acp object in some cases,
1618 # blindly looking for a # 'fail_part' key in the template can
1620 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
1621 $evt->{payload}->{fail_part} :
1624 $data->{renewal_response} = $evt;
1625 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1626 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1630 $ctx->{success_renewals} = $success_renewals;
1631 $ctx->{failed_renewals} = $failed_renewals;
1633 return Apache2::Const::OK;
1636 sub load_myopac_circ_history {
1638 my $e = $self->editor;
1639 my $ctx = $self->ctx;
1640 my $limit = $self->cgi->param('limit') || 15;
1641 my $offset = $self->cgi->param('offset') || 0;
1642 my $action = $self->cgi->param('action') || '';
1644 my $circ_handle_result;
1645 $circ_handle_result = $self->handle_circ_update($action) if $action;
1647 $ctx->{circ_history_limit} = $limit;
1648 $ctx->{circ_history_offset} = $offset;
1650 # Defer limitation to circ_history.tt2 when sorting
1651 if ($self->cgi->param('sort')) {
1656 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
1657 return Apache2::Const::OK;
1660 # if 'flesh' is set, copy data etc. is loaded and the return value is
1661 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
1663 sub fetch_user_circ_history {
1664 my ($self, $flesh, $limit, $offset) = @_;
1665 my $e = $self->editor;
1668 $limits{offset} = $offset if defined $offset;
1669 $limits{limit} = $limit if defined $limit;
1674 auch => ['target_copy','source_circ'],
1675 acp => ['call_number'],
1681 my $circs = $e->search_action_user_circ_history(
1683 {usr => $e->requestor->id},
1684 { # order newest to oldest by default
1685 order_by => {auch => 'xact_start DESC'},
1686 $flesh ? %flesh_ops : (),
1694 return $circs unless $flesh;
1698 my %unapi_cache = ();
1699 for my $circ (@$circs) {
1700 if ($circ->target_copy->call_number->id == -1) {
1703 marc_xml => undef # pre-cat copy, use the dummy title/author instead
1707 my $bre_id = $circ->target_copy->call_number->record->id;
1709 if (exists $unapi_cache{$bre_id}) {
1710 $unapi = $unapi_cache{$bre_id};
1712 my $result = $e->json_query({
1714 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
1718 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
1729 marc_xml => undef # failed, but try to go on
1738 sub handle_circ_update {
1741 my $circ_ids = shift;
1743 my $circ_ids //= [$self->cgi->param('circ_id')];
1745 if ($action =~ /delete/) {
1747 circ_ids => $circ_ids,
1752 'open-ils.actor.history.circ.clear',
1753 $self->editor->authtoken,
1761 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1762 sub load_myopac_hold_history {
1764 my $e = $self->editor;
1765 my $ctx = $self->ctx;
1766 my $limit = $self->cgi->param('limit') || 15;
1767 my $offset = $self->cgi->param('offset') || 0;
1768 $ctx->{hold_history_limit} = $limit;
1769 $ctx->{hold_history_offset} = $offset;
1771 my $hold_ids = $e->json_query({
1775 transform => 'action.usr_visible_holds',
1776 result_field => 'id'
1780 where => {id => $e->requestor->id}
1783 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1784 if($holds_object->{holds}) {
1785 $ctx->{holds} = $holds_object->{holds};
1787 $ctx->{hold_history_ids} = $holds_object->{all_ids};
1789 return Apache2::Const::OK;
1792 sub load_myopac_payment_form {
1796 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1797 $r = $self->prepare_extended_user_info and return $r;
1799 return Apache2::Const::OK;
1802 # TODO: add other filter options as params/configs/etc.
1803 sub load_myopac_payments {
1805 my $limit = $self->cgi->param('limit') || 20;
1806 my $offset = $self->cgi->param('offset') || 0;
1807 my $e = $self->editor;
1809 $self->ctx->{payment_history_limit} = $limit;
1810 $self->ctx->{payment_history_offset} = $offset;
1813 $args->{limit} = $limit if $limit;
1814 $args->{offset} = $offset if $offset;
1816 if (my $max_age = $self->ctx->{get_org_setting}->(
1817 $e->requestor->home_ou, "opac.payment_history_age_limit"
1819 my $min_ts = DateTime->now(
1820 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1821 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1823 $logger->info("XXX min_ts: $min_ts");
1824 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1827 $self->ctx->{payments} = $U->simplereq(
1829 'open-ils.actor.user.payments.retrieve.atomic',
1830 $e->authtoken, $e->requestor->id, $args);
1832 return Apache2::Const::OK;
1835 # 1. caches the form parameters
1836 # 2. loads the credit card payment "Processing..." page
1837 sub load_myopac_pay_init {
1839 my $cache = OpenSRF::Utils::Cache->new('global');
1841 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1843 if (!@payment_xacts) {
1844 # for consistency with load_myopac_payment_form() and
1845 # to preserve backwards compatibility, if no xacts are
1846 # selected, assume all (applicable) transactions are wanted.
1847 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1848 return $stat if $stat;
1850 map { $_->{xact}->id } (
1851 @{$self->ctx->{fines}->{circulation}},
1852 @{$self->ctx->{fines}->{grocery}}
1856 return $self->generic_redirect unless @payment_xacts;
1858 my $cc_args = {"where_process" => 1};
1860 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1861 number cvv2 expire_year expire_month billing_first
1862 billing_last billing_address billing_city billing_state
1863 billing_zip stripe_token
1867 cc_args => $cc_args,
1868 user => $self->ctx->{user}->id,
1869 xacts => \@payment_xacts
1872 # generate a temporary cache token and cache the form data
1873 my $token = md5_hex($$ . time() . rand());
1874 $cache->put_cache($token, $cache_args, 30);
1876 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1878 # after we render the processing page, we quickly redirect to submit
1879 # the actual payment. The refresh url contains the payment token.
1880 # It also contains the list of xact IDs, which allows us to clear the
1881 # cache at the earliest possible time while leaving a trace of which
1882 # transactions we were processing, so the UI can bring the user back
1883 # to the payment form w/ the same xacts if the payment fails.
1885 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1886 $refresh .= ";xact=$_" for @payment_xacts;
1887 $self->ctx->{refresh} = $refresh;
1889 return Apache2::Const::OK;
1892 # retrieve the cached CC payment info and send off for processing
1893 sub load_myopac_pay {
1895 my $token = $self->ctx->{page_args}->[0];
1896 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1898 my $cache = OpenSRF::Utils::Cache->new('global');
1899 my $cache_args = $cache->get_cache($token);
1900 $cache->delete_cache($token);
1902 # this page is loaded immediately after the token is created.
1903 # if the cached data is not there, it's because of an invalid
1904 # token (or cache failure) and not because of a timeout.
1905 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1907 my @payment_xacts = @{$cache_args->{xacts}};
1908 my $cc_args = $cache_args->{cc_args};
1910 # as an added security check, verify the user submitting
1911 # the form is the same as the user whose data was cached
1912 return Apache2::Const::HTTP_BAD_REQUEST unless
1913 $cache_args->{user} == $self->ctx->{user}->id;
1915 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1918 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1920 # balance_owed is computed specifically from the fines we're paying
1921 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1922 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1923 return Apache2::Const::HTTP_BAD_REQUEST;
1927 "cc_args" => $cc_args,
1928 "userid" => $self->ctx->{user}->id,
1929 "payment_type" => "credit_card_payment",
1930 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1933 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1934 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1937 $self->ctx->{"payment_response"} = $resp;
1939 unless ($resp->{"textcode"}) {
1940 $self->ctx->{printable_receipt} = $U->simplereq(
1941 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1942 $self->editor->authtoken, $resp->{payments}
1946 return Apache2::Const::OK;
1949 sub load_myopac_receipt_print {
1952 $self->ctx->{printable_receipt} = $U->simplereq(
1953 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1954 $self->editor->authtoken, [$self->cgi->param("payment")]
1957 return Apache2::Const::OK;
1960 sub load_myopac_receipt_email {
1963 # The following ML method doesn't actually check whether the user in
1964 # question has an email address, so we do.
1965 if ($self->ctx->{user}->email) {
1966 $self->ctx->{email_receipt_result} = $U->simplereq(
1967 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1968 $self->editor->authtoken, [$self->cgi->param("payment")]
1971 $self->ctx->{email_receipt_result} =
1972 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1975 return Apache2::Const::OK;
1979 my ($self, $limit, $offset, $id_list) = @_;
1981 # XXX TODO: check for failure after various network calls
1983 # It may be unclear, but this result structure lumps circulation and
1984 # reservation fines together, and keeps grocery fines separate.
1985 $self->ctx->{"fines"} = {
1986 "circulation" => [],
1993 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1995 # TODO: This should really be a ML call, but the existing calls
1996 # return an excessive amount of data and don't offer streaming
1998 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2000 my $req = $cstore->request(
2001 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2003 usr => $self->editor->requestor->id,
2004 balance_owed => {'!=' => 0},
2005 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2010 mobts => [qw/grocery circulation reservation/],
2011 bresv => ['target_resource_type'],
2015 circ => ['target_copy'],
2016 acp => ['call_number'],
2019 order_by => { mobts => 'xact_start' },
2024 # Collect $$ amounts from each transaction for summing below.
2025 my (@paid_amounts, @owed_amounts, @balance_amounts);
2027 while(my $resp = $req->recv) {
2028 my $mobts = $resp->content;
2029 my $circ = $mobts->circulation;
2032 if($mobts->grocery) {
2033 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2034 $last_billing = pop(@billings);
2037 push(@paid_amounts, $mobts->total_paid);
2038 push(@owed_amounts, $mobts->total_owed);
2039 push(@balance_amounts, $mobts->balance_owed);
2041 my $marc_xml = undef;
2042 if ($mobts->xact_type eq 'reservation' and
2043 $mobts->reservation->target_resource_type->record) {
2044 $marc_xml = XML::LibXML->new->parse_string(
2045 $mobts->reservation->target_resource_type->record->marc
2047 } elsif ($mobts->xact_type eq 'circulation' and
2048 $circ->target_copy->call_number->id != -1) {
2049 $marc_xml = XML::LibXML->new->parse_string(
2050 $circ->target_copy->call_number->record->marc
2055 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2058 last_grocery_billing => $last_billing,
2059 marc_xml => $marc_xml
2066 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2067 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2068 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2073 sub prepare_fines_for_payment {
2074 # This assumes $self->prepare_fines has already been run
2078 if ($self->ctx->{fines}) {
2079 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2080 @{$self->ctx->{fines}->{circulation}},
2081 @{$self->ctx->{fines}->{grocery}}
2088 sub load_myopac_main {
2090 my $limit = $self->cgi->param('limit') || 0;
2091 my $offset = $self->cgi->param('offset') || 0;
2092 $self->ctx->{search_ou} = $self->_get_search_lib();
2093 $self->ctx->{user}->notes(
2094 $self->editor->search_actor_usr_note({
2095 usr => $self->ctx->{user}->id,
2099 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2102 sub load_myopac_update_email {
2104 my $e = $self->editor;
2105 my $ctx = $self->ctx;
2106 my $email = $self->cgi->param('email') || '';
2107 my $current_pw = $self->cgi->param('current_pw') || '';
2109 # needed for most up-to-date email address
2110 if (my $r = $self->prepare_extended_user_info) { return $r };
2112 return Apache2::Const::OK
2113 unless $self->cgi->request_method eq 'POST';
2115 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2116 $ctx->{invalid_email} = $email;
2117 return Apache2::Const::OK;
2120 my $stat = $U->simplereq(
2122 'open-ils.actor.user.email.update',
2123 $e->authtoken, $email, $current_pw);
2125 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2126 $ctx->{password_incorrect} = 1;
2127 return Apache2::Const::OK;
2130 unless ($self->cgi->param("redirect_to")) {
2131 my $url = $self->apache->unparsed_uri;
2132 $url =~ s/update_email/prefs/;
2134 return $self->generic_redirect($url);
2137 return $self->generic_redirect;
2140 sub load_myopac_update_username {
2142 my $e = $self->editor;
2143 my $ctx = $self->ctx;
2144 my $username = $self->cgi->param('username') || '';
2145 my $current_pw = $self->cgi->param('current_pw') || '';
2147 $self->prepare_extended_user_info;
2149 my $allow_change = 1;
2151 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2152 if(defined($lock_usernames) and $lock_usernames == 1) {
2153 # Policy says no username changes
2156 # We want this further down.
2157 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2158 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2159 if(!$username_unlimit) {
2161 # Default is "starts with a number"
2162 $regex_check = '^\d+';
2164 # You already have a username?
2165 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2170 if(!$allow_change) {
2171 my $url = $self->apache->unparsed_uri;
2172 $url =~ s/update_username/prefs/;
2174 return $self->generic_redirect($url);
2177 return Apache2::Const::OK
2178 unless $self->cgi->request_method eq 'POST';
2180 unless($username and $username !~ /\s/) { # any other username restrictions?
2181 $ctx->{invalid_username} = $username;
2182 return Apache2::Const::OK;
2185 # New username can't look like a barcode if we have a barcode regex
2186 if($regex_check and $username =~ /$regex_check/) {
2187 $ctx->{invalid_username} = $username;
2188 return Apache2::Const::OK;
2191 # New username has to look like a username if we have a username regex
2192 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2193 if($regex_check and $username !~ /$regex_check/) {
2194 $ctx->{invalid_username} = $username;
2195 return Apache2::Const::OK;
2198 if($username ne $e->requestor->usrname) {
2200 my $evt = $U->simplereq(
2202 'open-ils.actor.user.username.update',
2203 $e->authtoken, $username, $current_pw);
2205 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2206 $ctx->{password_incorrect} = 1;
2207 return Apache2::Const::OK;
2210 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2211 $ctx->{username_exists} = $username;
2212 return Apache2::Const::OK;
2216 my $url = $self->apache->unparsed_uri;
2217 $url =~ s/update_username/prefs/;
2219 return $self->generic_redirect($url);
2222 sub load_myopac_update_password {
2224 my $e = $self->editor;
2225 my $ctx = $self->ctx;
2227 return Apache2::Const::OK
2228 unless $self->cgi->request_method eq 'POST';
2230 my $current_pw = $self->cgi->param('current_pw') || '';
2231 my $new_pw = $self->cgi->param('new_pw') || '';
2232 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2234 unless($new_pw eq $new_pw2) {
2235 $ctx->{password_nomatch} = 1;
2236 return Apache2::Const::OK;
2239 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2242 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2243 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2246 if($pw_regex and $new_pw !~ /$pw_regex/) {
2247 $ctx->{password_invalid} = 1;
2248 return Apache2::Const::OK;
2251 my $evt = $U->simplereq(
2253 'open-ils.actor.user.password.update',
2254 $e->authtoken, $new_pw, $current_pw);
2257 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2258 $ctx->{password_incorrect} = 1;
2259 return Apache2::Const::OK;
2262 my $url = $self->apache->unparsed_uri;
2263 $url =~ s/update_password/prefs/;
2265 return $self->generic_redirect($url);
2268 sub _update_bookbag_metadata {
2269 my ($self, $bookbag) = @_;
2271 $bookbag->name($self->cgi->param("name"));
2272 $bookbag->description($self->cgi->param("description"));
2274 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2278 sub _get_lists_per_page {
2281 if($self->editor->requestor) {
2282 $self->timelog("Checking for opac.lists_per_page preference");
2283 # See if the user has a lists per page preference
2284 my $ipp = $self->editor->search_actor_user_setting({
2285 usr => $self->editor->requestor->id,
2286 name => 'opac.lists_per_page'
2288 $self->timelog("Got opac.lists_per_page preference");
2289 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2291 return 10; # default
2294 sub _get_items_per_page {
2297 if($self->editor->requestor) {
2298 $self->timelog("Checking for opac.list_items_per_page preference");
2299 # See if the user has a list items per page preference
2300 my $ipp = $self->editor->search_actor_user_setting({
2301 usr => $self->editor->requestor->id,
2302 name => 'opac.list_items_per_page'
2304 $self->timelog("Got opac.list_items_per_page preference");
2305 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2307 return 10; # default
2310 sub load_myopac_bookbags {
2312 my $e = $self->editor;
2313 my $ctx = $self->ctx;
2314 my $limit = $self->_get_lists_per_page || 10;
2315 my $offset = $self->cgi->param('offset') || 0;
2317 $ctx->{bookbags_limit} = $limit;
2318 $ctx->{bookbags_offset} = $offset;
2320 # for list item pagination
2321 my $item_limit = $self->_get_items_per_page;
2322 my $item_page = $self->cgi->param('item_page') || 1;
2323 my $item_offset = ($item_page - 1) * $item_limit;
2324 $ctx->{bookbags_item_page} = $item_page;
2326 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2327 $e->xact_begin; # replication...
2329 my $rv = $self->load_mylist;
2330 unless($rv eq Apache2::Const::OK) {
2335 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2337 {owner => $e->requestor->id, btype => 'bookbag'}, {
2338 order_by => {cbreb => 'name'},
2346 if(!$ctx->{bookbags}) {
2348 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2351 # We load the user prefs to get their default bookbag.
2352 $self->_load_user_with_prefs;
2354 # We also want a total count of the user's bookbags.
2356 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2358 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2360 my $r = $e->json_query($q);
2361 $ctx->{bookbag_count} = $r->[0]->{'count'};
2363 # If the user wants a specific bookbag's items, load them.
2365 if ($self->cgi->param("bbid")) {
2367 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2370 my $query = $self->_prepare_bookbag_container_query(
2371 $bookbag->id, $sorter, $modifier
2374 # Calculate total count of the items in selected bookbag.
2375 # This total includes record entries that have no assets available.
2376 my $bb_search_results = $U->simplereq(
2377 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2378 {"limit" => 1, "offset" => 0}, $query
2379 ); # we only need the count, so do the actual search with limit=1
2381 if ($bb_search_results) {
2382 $ctx->{bb_item_count} = $bb_search_results->{count};
2384 $logger->warn("search failed in load_myopac_bookbags()");
2385 $ctx->{bb_item_count} = 0; # fallback value
2388 #calculate page count
2389 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2391 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2392 if (!$self->_update_bookbag_metadata($bookbag)) {
2394 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2397 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2400 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2401 if ($self->cgi->param($param)) {
2402 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
2406 return $self->generic_redirect($url);
2410 # we're done with our CStoreEditor. Rollback here so
2411 # later calls don't cause a timeout, resulting in a
2412 # transaction rollback under the covers.
2416 # For list items pagination
2418 "limit" => $item_limit,
2419 "offset" => $item_offset
2422 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2423 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2425 # capture pref_ou for callnumber filter/display
2426 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2428 # search for local callnumbers for display
2429 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2431 my (undef, @recs) = $self->get_records_and_facets(
2432 [ map {$_->target_biblio_record_entry->id} @$items ],
2435 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2437 site => $ctx->{get_aou}->($focus_ou)->shortname,
2438 pref_lib => $ctx->{pref_ou}
2442 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2444 $bookbag->items($items);
2448 # If we have add_rec, we got here from the "Add to new list"
2449 # or "See all" popmenu items.
2450 if (my $add_rec = $self->cgi->param('add_rec')) {
2451 $self->ctx->{add_rec} = $add_rec;
2452 # But not in the staff client, 'cause that breaks things.
2453 unless ($self->ctx->{is_staff}) {
2454 # allow caller to provide the where_from in cases where
2455 # the referer is an intermediate error page
2456 if ($self->cgi->param('where_from')) {
2457 $self->ctx->{where_from} = $self->cgi->param('where_from');
2459 $self->ctx->{where_from} = $self->ctx->{referer};
2460 if ( my $anchor = $self->cgi->param('anchor') ) {
2461 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2467 # this rollback may be a dupe, but that's OK because
2468 # cstoreditor ignores dupe rollbacks
2471 return Apache2::Const::OK;
2475 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
2476 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2477 sub load_myopac_bookbag_update {
2478 my ($self, $action, $list_id, @hold_recs) = @_;
2479 my $e = $self->editor;
2480 my $cgi = $self->cgi;
2482 # save_notes is effectively another action, but is passed in a separate
2483 # CGI parameter for what are really just layout reasons.
2484 $action = 'save_notes' if $cgi->param('save_notes');
2485 $action ||= $cgi->param('action');
2487 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2489 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2490 my @selected_item = $cgi->param('selected_item');
2491 my $shared = $cgi->param('shared');
2492 my $name = $cgi->param('name');
2493 my $description = $cgi->param('description');
2497 # This url intentionally leaves off the edit_notes parameter, but
2498 # may need to add some back in for paging.
2500 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2501 $self->ctx->{opac_root} . "/myopac/lists?";
2503 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2504 if ($cgi->param($param)) {
2505 $url .= "$param=" . uri_escape_utf8($cgi->param($param)) . ";";
2509 if ($action eq 'create') {
2512 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2514 $list->description($description);
2515 $list->owner($e->requestor->id);
2516 $list->btype('bookbag');
2517 $list->pub($shared ? 't' : 'f');
2518 $success = $U->simplereq('open-ils.actor',
2519 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2520 if (ref($success) ne 'HASH' && scalar @add_rec) {
2521 $list_id = (ref($success)) ? $success->id : $success;
2522 foreach my $add_rec (@add_rec) {
2523 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2524 $item->bucket($list_id);
2525 $item->target_biblio_record_entry($add_rec);
2526 $success = $U->simplereq('open-ils.actor',
2527 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2528 last unless $success;
2531 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
2534 $self->ctx->{bucket_failure_noname} = 1;
2537 } elsif($action eq 'place_hold') {
2539 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
2540 unless (@hold_recs) {
2541 if (@selected_item) {
2542 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
2543 @hold_recs = map { $_->target_biblio_record_entry } @$items;
2547 return Apache2::Const::OK unless @hold_recs;
2548 $logger->info("placing holds from list page on: @hold_recs");
2550 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
2551 $url .= ';hold_target=' . $_ for @hold_recs;
2552 foreach my $param (('loc', 'qtype', 'query')) {
2553 if ($cgi->param($param)) {
2554 $url .= ";$param=" . uri_escape_utf8($cgi->param($param));
2557 return $self->generic_redirect($url);
2561 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
2563 return Apache2::Const::HTTP_BAD_REQUEST unless
2564 $list and $list->owner == $e->requestor->id;
2567 if($action eq 'delete') {
2568 $success = $U->simplereq('open-ils.actor',
2569 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
2571 # We check to see if we're deleting the user's default list.
2572 $self->_load_user_with_prefs;
2573 my $settings_map = $self->ctx->{user_setting_map};
2574 if ($$settings_map{'opac.default_list'} == $list_id) {
2575 # We unset the user's opac.default_list setting.
2576 $success = $U->simplereq(
2578 'open-ils.actor.patron.settings.update',
2581 { 'opac.default_list' => 0 }
2585 } elsif($action eq 'show') {
2586 unless($U->is_true($list->pub)) {
2588 $success = $U->simplereq('open-ils.actor',
2589 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2592 } elsif($action eq 'hide') {
2593 if($U->is_true($list->pub)) {
2595 $success = $U->simplereq('open-ils.actor',
2596 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2599 } elsif($action eq 'rename') {
2602 $success = $U->simplereq('open-ils.actor',
2603 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2606 } elsif($action eq 'add_rec') {
2607 foreach my $add_rec (@add_rec) {
2608 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2609 $item->bucket($list_id);
2610 $item->target_biblio_record_entry($add_rec);
2611 $success = $U->simplereq('open-ils.actor',
2612 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2613 last unless $success;
2615 # Redirect back where we came from if we have an anchor parameter:
2616 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
2617 $url = $self->ctx->{referer};
2618 $url =~ s/#.*|$/#$anchor/;
2619 } elsif ($cgi->param('where_from')) {
2620 # Or, if we have a "where_from" parameter.
2621 $url = $cgi->param('where_from');
2623 } elsif ($action eq 'del_item') {
2624 foreach (@selected_item) {
2625 $success = $U->simplereq(
2627 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
2629 last unless $success;
2631 } elsif ($action eq 'save_notes') {
2632 $success = $self->update_bookbag_item_notes;
2633 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
2634 } elsif ($action eq 'make_default') {
2635 $success = $U->simplereq(
2637 'open-ils.actor.patron.settings.update',
2640 { 'opac.default_list' => $list_id }
2642 } elsif ($action eq 'remove_default') {
2643 $success = $U->simplereq(
2645 'open-ils.actor.patron.settings.update',
2648 { 'opac.default_list' => 0 }
2652 return $self->generic_redirect($url) if $success;
2654 $self->ctx->{where_from} = $cgi->param('where_from');
2655 $self->ctx->{bucket_action} = $action;
2656 $self->ctx->{bucket_action_failed} = 1;
2657 return Apache2::Const::OK;
2660 sub update_bookbag_item_notes {
2662 my $e = $self->editor;
2664 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2665 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2667 # We're going to leverage an API call that's already been written to check
2668 # permissions appropriately.
2670 my $a = create OpenSRF::AppSession("open-ils.actor");
2671 my $method = "open-ils.actor.container.item_note.cud";
2673 for my $note_key (@note_keys) {
2676 my $id = ($note_key =~ /(\d+)/)[0];
2679 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2680 my $event = $e->die_event;
2681 $self->apache->log->warn(
2682 "error retrieving cbrebin id $id, got event " .
2686 $self->ctx->{bucket_action_event} = $event;
2690 if (length($self->cgi->param($note_key))) {
2691 $note->ischanged(1);
2692 $note->note($self->cgi->param($note_key));
2694 $note->isdeleted(1);
2697 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2699 if (defined $U->event_code($r)) {
2700 $self->apache->log->warn(
2701 "attempt to modify cbrebin " . $note->id .
2702 " returned event " . $r->{textcode}
2706 $self->ctx->{bucket_action_event} = $r;
2711 for my $item_key (@item_keys) {
2712 my $id = int(($item_key =~ /(\d+)/)[0]);
2713 my $text = $self->cgi->param($item_key);
2716 next unless length $text;
2718 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2723 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2725 if (defined $U->event_code($r)) {
2726 $self->apache->log->warn(
2727 "attempt to create cbrebin for item " . $note->item .
2728 " returned event " . $r->{textcode}
2732 $self->ctx->{bucket_action_event} = $r;
2741 sub load_myopac_bookbag_print {
2744 my $id = int($self->cgi->param("list"));
2746 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2749 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2753 # Get the bookbag object itself, assuming we're allowed to.
2754 if ($self->editor->allowed("VIEW_CONTAINER")) {
2756 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2758 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2762 "owner" => $self->editor->requestor->id,
2766 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2768 $bbag = pop @$bookbags;
2771 # If we have a bookbag we're allowed to look at, issue the A/T event
2772 # to get CSV, passing as a user param that search query we built before.
2774 $self->ctx->{csv} = $U->fire_object_event(
2775 undef, "container.biblio_record_entry_bucket.csv",
2776 $bbag, $self->editor->requestor->home_ou,
2777 undef, {"item_search" => $item_search}
2781 # Create a reasonable filename and set the content disposition to
2782 # provoke browser download dialogs.
2783 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2785 return $self->set_file_download_headers("$filename.csv");
2788 sub load_myopac_circ_history_export {
2790 my $e = $self->editor;
2791 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2793 my $circs = $self->fetch_user_circ_history(1);
2795 $self->ctx->{csv}->{circs} = $circs;
2796 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
2800 sub load_password_reset {
2802 my $cgi = $self->cgi;
2803 my $ctx = $self->ctx;
2804 my $barcode = $cgi->param('barcode');
2805 my $username = $cgi->param('username');
2806 my $email = $cgi->param('email');
2807 my $pwd1 = $cgi->param('pwd1');
2808 my $pwd2 = $cgi->param('pwd2');
2809 my $uuid = $ctx->{page_args}->[0];
2813 $logger->info("patron password reset with uuid $uuid");
2815 if ($pwd1 and $pwd2) {
2817 if ($pwd1 eq $pwd2) {
2819 my $response = $U->simplereq(
2821 'open-ils.actor.patron.password_reset.commit',
2824 $logger->info("patron password reset response " . Dumper($response));
2826 if ($U->event_code($response)) { # non-success event
2828 my $code = $response->{textcode};
2830 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2831 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2834 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2835 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2840 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2843 } else { # passwords not equal
2845 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2848 } else { # 2 password values needed
2850 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2853 } elsif ($barcode or $username) {
2855 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2856 push(@params, $email) if $email;
2860 'open-ils.actor.patron.password_reset.request', @params);
2862 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2865 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2866 return Apache2::Const::OK;