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';
17 use List::MoreUtils qw/uniq/;
19 sub prepare_extended_user_info {
22 my $e = $self->editor;
24 # are we already in a transaction?
25 my $local_xact = !$e->{xact_id};
26 $e->xact_begin if $local_xact;
28 # keep the original user object so we can restore
29 # login-specific data (e.g. workstation)
30 my $usr = $self->ctx->{user};
32 $self->ctx->{user} = $self->editor->retrieve_actor_user([
33 $self->ctx->{user}->id,
37 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
43 $e->rollback if $local_xact;
45 $self->ctx->{user}->wsid($usr->wsid);
46 $self->ctx->{user}->ws_ou($usr->ws_ou);
48 # discard replaced (negative-id) addresses.
49 $self->ctx->{user}->addresses([
50 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
52 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
53 unless $self->ctx->{user};
58 # Given an event returned by a failed attempt to create a hold, do we have
59 # permission to override? XXX Should the permission check be scoped to a
60 # given org_unit context?
61 sub test_could_override {
62 my ($self, $event) = @_;
64 return 0 unless $event;
65 return 1 if $self->editor->allowed($event->{textcode} . ".override");
66 return 1 if $event->{"fail_part"} and
67 $self->editor->allowed($event->{"fail_part"} . ".override");
71 # Find out whether we care that local copies are available
72 sub local_avail_concern {
73 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
75 my $would_block = $self->ctx->{get_org_setting}->
76 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
78 $self->ctx->{get_org_setting}->
79 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
80 not $self->cgi->param("override")
81 ) unless $would_block;
83 if ($would_block or $would_alert) {
85 "hold_target" => $hold_target,
86 "hold_type" => $hold_type,
87 "org_unit" => $pickup_lib
89 my $local_avail = $U->simplereq(
91 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
94 "copy availability information for " . Dumper($args) .
95 " is " . Dumper($local_avail)
97 if (%$local_avail) { # if hash not empty
98 $self->ctx->{hold_copy_available} = $local_avail;
99 return ($would_block, $would_alert);
107 # user : au object, fleshed
108 sub load_myopac_prefs {
110 my $cgi = $self->cgi;
111 my $e = $self->editor;
112 my $pending_addr = $cgi->param('pending_addr');
113 my $replace_addr = $cgi->param('replace_addr');
114 my $delete_pending = $cgi->param('delete_pending');
116 $self->prepare_extended_user_info;
117 my $user = $self->ctx->{user};
119 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
120 if(defined($lock_usernames) and $lock_usernames == 1) {
121 # Policy says no username changes
122 $self->ctx->{username_change_disallowed} = 1;
124 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
125 if(!$username_unlimit) {
126 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
128 # Default is "starts with a number"
129 $regex_check = '^\d+';
131 # You already have a username?
132 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
133 $self->ctx->{username_change_disallowed} = 1;
138 return Apache2::Const::OK unless
139 $pending_addr or $replace_addr or $delete_pending;
141 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
144 if( $pending_addr ) { # update an existing pending address
146 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
147 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
148 $paddr->$_( $cgi->param($_) ) for @form_fields;
150 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
152 $paddr = Fieldmapper::actor::user_address->new;
154 $paddr->usr($user->id);
155 $paddr->pending('t');
156 $paddr->replaces($replace_addr);
157 $paddr->$_( $cgi->param($_) ) for @form_fields;
159 } elsif( $delete_pending ) {
160 $paddr = $e->retrieve_actor_user_address($delete_pending);
161 return Apache2::Const::HTTP_BAD_REQUEST unless
162 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
163 $paddr->isdeleted(1);
166 my $resp = $U->simplereq(
168 'open-ils.actor.user.address.pending.cud',
169 $e->authtoken, $paddr);
171 if( $U->event_code($resp) ) {
172 $logger->error("Error updating pending address: $resp");
173 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
176 # in light of these changes, re-fetch latest data
178 $self->prepare_extended_user_info;
181 return Apache2::Const::OK;
184 sub load_myopac_prefs_notify {
186 my $e = $self->editor;
189 my $stat = $self->_load_user_with_prefs;
190 return $stat if $stat;
192 my $user_prefs = $self->fetch_optin_prefs;
193 $user_prefs = $self->update_optin_prefs($user_prefs)
194 if $self->cgi->request_method eq 'POST';
196 $self->ctx->{opt_in_settings} = $user_prefs;
198 return Apache2::Const::OK
199 unless $self->cgi->request_method eq 'POST';
202 my $set_map = $self->ctx->{user_setting_map};
206 opac.default_sms_notify
208 my $val = $self->cgi->param($key);
209 $settings{$key}= $val unless $$set_map{$key} eq $val;
212 my $key = 'opac.default_sms_carrier';
213 my $val = $self->cgi->param('sms_carrier');
214 $settings{$key}= $val unless $$set_map{$key} eq $val;
216 $key = 'opac.hold_notify';
217 my @notify_methods = ();
218 if ($self->cgi->param($key . ".email") eq 'on') {
219 push @notify_methods, "email";
221 if ($self->cgi->param($key . ".phone") eq 'on') {
222 push @notify_methods, "phone";
224 if ($self->cgi->param($key . ".sms") eq 'on') {
225 push @notify_methods, "sms";
227 $val = join("|",@notify_methods);
228 $settings{$key}= $val unless $$set_map{$key} eq $val;
230 # Send the modified settings off to be saved
233 'open-ils.actor.patron.settings.update',
234 $self->editor->authtoken, undef, \%settings);
236 # re-fetch user prefs
237 $self->ctx->{updated_user_settings} = \%settings;
238 return $self->_load_user_with_prefs || Apache2::Const::OK;
241 sub fetch_optin_prefs {
243 my $e = $self->editor;
245 # fetch all of the opt-in settings the user has access to
246 # XXX: user's should in theory have options to opt-in to notices
247 # for remote locations, but that opens the door for a large
248 # set of generally un-used opt-ins.. needs discussion
249 my $opt_ins = $U->simplereq(
251 'open-ils.actor.event_def.opt_in.settings.atomic',
252 $e->authtoken, $e->requestor->home_ou);
254 # some opt-ins are staff-only
255 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
257 # fetch user setting values for each of the opt-in settings
258 my $user_set = $U->simplereq(
260 'open-ils.actor.patron.settings.retrieve',
263 [map {$_->name} @$opt_ins]
266 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
269 sub load_myopac_messages {
271 my $e = $self->editor;
272 my $ctx = $self->ctx;
273 my $cgi = $self->cgi;
275 my $limit = $cgi->param('limit') || 20;
276 my $offset = $cgi->param('offset') || 0;
278 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
281 my $action = $cgi->param('action') || '';
283 my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
284 if ($changed > 0 || $failed > 0) {
285 $ctx->{message_update_action} = $action;
286 $ctx->{message_update_changed} = $changed;
287 $ctx->{message_update_failed} = $failed;
288 $self->update_dashboard_stats();
292 my $single = $cgi->param('single') || 0;
293 my $id = $cgi->param('message_id');
297 if (!$action && $single && $id) {
298 $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
299 if (scalar(@$messages) == 1) {
300 $ctx->{display_single_message} = 1;
301 $ctx->{patron_message_id} = $id;
307 # fetch all the messages
308 ($ctx->{patron_messages_count}, $messages) =
309 $self->_fetch_user_messages($pcrud, $offset, $limit);
314 foreach my $aum (@$messages) {
316 push @{ $ctx->{patron_messages} }, {
318 title => $aum->title,
319 message => $aum->message,
320 create_date => $aum->create_date,
321 is_read => defined($aum->read_date) ? 1 : 0,
322 library => $aum->sending_lib->name,
326 $ctx->{patron_messages_limit} = $limit;
327 $ctx->{patron_messages_offset} = $offset;
329 return Apache2::Const::OK;
332 sub _fetch_and_mark_read_single_message {
337 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
338 my $messages = $pcrud->request(
339 'open-ils.pcrud.search.auml.atomic',
340 $self->editor->authtoken,
342 usr => $self->editor->requestor->id,
348 flesh_fields => { auml => ['sending_lib'] },
352 $messages->[0]->read_date('now');
354 'open-ils.pcrud.update.auml',
355 $self->editor->authtoken,
359 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
361 $self->update_dashboard_stats();
366 sub _fetch_user_messages {
372 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
374 my $all_messages = $pcrud->request(
375 'open-ils.pcrud.id_list.auml.atomic',
376 $self->editor->authtoken,
378 usr => $self->editor->requestor->id,
384 my $messages = $pcrud->request(
385 'open-ils.pcrud.search.auml.atomic',
386 $self->editor->authtoken,
388 usr => $self->editor->requestor->id,
393 flesh_fields => { auml => ['sending_lib'] },
394 order_by => { auml => 'create_date DESC' },
399 return scalar(@$all_messages), $messages;
402 sub _handle_message_action {
406 my $cgi = $self->cgi;
408 my @ids = $cgi->param('message_id');
409 return (0, 0) unless @ids;
413 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
415 my $aum = $pcrud->request(
416 'open-ils.pcrud.retrieve.auml',
417 $self->editor->authtoken,
421 if ($action eq 'mark_read') {
422 $aum->read_date('now');
423 } elsif ($action eq 'mark_unread') {
424 $aum->clear_read_date();
425 } elsif ($action eq 'mark_deleted') {
428 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
433 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
435 $failed = scalar(@ids);
437 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
439 return ($changed, $failed);
442 sub _load_lists_and_settings {
444 my $e = $self->editor;
445 my $stat = $self->_load_user_with_prefs;
448 my $setting_map = $self->ctx->{user_setting_map};
449 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
450 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
452 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
453 order_by => {cbreb => 'name'},
454 limit => $self->cgi->param('limit') || 10,
455 offset => $self->cgi->param('offset') || 0
459 # We also want a total count of the user's bookbags.
461 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
463 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
465 my $r = $e->json_query($q);
466 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
467 # Someone has requested that we use the default list's name
468 # rather than "Default List."
471 'select' => {'cbreb' => ['name']},
473 'where' => {'id' => $exclude}
475 $r = $e->json_query($q);
476 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
484 sub update_optin_prefs {
486 my $user_prefs = shift;
487 my $e = $self->editor;
488 my @settings = $self->cgi->param('setting');
491 # apply now-true settings
492 for my $applied (@settings) {
493 # see if setting is already applied to this user
494 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
495 $newsets{$applied} = OpenSRF::Utils::JSON->true;
498 # remove now-false settings
499 for my $pref (grep { $_->{value} } @$user_prefs) {
500 $newsets{$pref->{cust}->name} = undef
501 unless grep { $_ eq $pref->{cust}->name } @settings;
506 'open-ils.actor.patron.settings.update',
507 $e->authtoken, $e->requestor->id, \%newsets);
509 # update the local prefs to match reality
510 for my $pref (@$user_prefs) {
511 $pref->{value} = $newsets{$pref->{cust}->name}
512 if exists $newsets{$pref->{cust}->name};
518 sub _load_user_with_prefs {
520 my $stat = $self->prepare_extended_user_info('settings');
521 return $stat if $stat; # not-OK
523 $self->ctx->{user_setting_map} = {
524 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
525 @{$self->ctx->{user}->settings}
531 sub _get_bookbag_sort_params {
532 my ($self, $param_name) = @_;
534 # The interface that feeds this cgi parameter will provide a single
535 # argument for a QP sort filter, and potentially a modifier after a period.
536 # In practice this means the "sort" parameter will be something like
537 # "titlesort" or "authorsort.descending".
538 my $sorter = $self->cgi->param($param_name) || "";
541 $sorter =~ s/^(.*?)\.(.*)/$1/;
542 $modifier = $2 || undef;
545 return ($sorter, $modifier);
548 sub _prepare_bookbag_container_query {
549 my ($self, $container_id, $sorter, $modifier) = @_;
552 "container(bre,bookbag,%d,%s)%s%s",
553 $container_id, $self->editor->authtoken,
554 ($sorter ? " sort($sorter)" : ""),
555 ($modifier ? "#$modifier" : "")
559 sub _prepare_anonlist_sorting_query {
560 my ($self, $list, $sorter, $modifier) = @_;
563 "record_list(%s)%s%s",
565 ($sorter ? " sort($sorter)" : ""),
566 ($modifier ? "#$modifier" : "")
571 sub load_myopac_prefs_settings {
576 opac.default_search_location
577 opac.default_pickup_location
578 opac.temporary_list_no_warn
581 my $stat = $self->_load_user_with_prefs;
582 return $stat if $stat;
584 # if behind-desk holds are supported and the user
585 # setting which controls the value is opac-visible,
586 # add the setting to the list of settings to manage.
587 # note: this logic may need to be changed later to
588 # check whether behind-the-desk holds are supported
589 # anywhere the patron may select as a pickup lib.
590 my $e = $self->editor;
591 my $bdous = $self->ctx->{get_org_setting}->(
592 $e->requestor->home_ou,
593 'circ.holds.behind_desk_pickup_supported');
597 $e->retrieve_config_usr_setting_type(
598 'circ.holds_behind_desk');
600 if ($U->is_true($setting->opac_visible)) {
601 push(@user_prefs, 'circ.holds_behind_desk');
602 $self->ctx->{behind_desk_supported} = 1;
606 return Apache2::Const::OK
607 unless $self->cgi->request_method eq 'POST';
609 # some setting values from the form don't match the
610 # required value/format for the db, so they have to be
611 # individually translated.
614 my $set_map = $self->ctx->{user_setting_map};
616 foreach my $key (@user_prefs) {
617 my $val = $self->cgi->param($key);
618 $settings{$key}= $val unless $$set_map{$key} eq $val;
621 # Used by the settings update form when warning on history delete.
622 my $clear_circ_history = 0;
623 my $clear_hold_history = 0;
625 # true if we need to show the warning on next page load.
626 my $hist_warning_needed = 0;
627 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
629 my $now = DateTime->now->strftime('%F');
631 qw/history.circ.retention_start history.hold.retention_start/) {
633 my $val = $self->cgi->param($key);
634 if($val and $val eq 'on') {
635 # Set the start time to 'now' unless a start time already exists for the user
636 $settings{$key} = $now unless $$set_map{$key};
640 next unless $$set_map{$key}; # nothing to do
642 $clear_circ_history = 1 if $key =~ /circ/;
643 $clear_hold_history = 1 if $key =~ /hold/;
645 if (!$hist_clear_confirmed) {
646 # when clearing circ history, only warn if history data exists.
648 if ($clear_circ_history) {
650 if ($self->fetch_user_circ_history(0, 1)->[0]) {
651 $hist_warning_needed = 1;
652 next; # no history updates while confirmation pending
657 my $one_hold = $e->json_query({
661 transform => 'action.usr_visible_holds',
666 where => {id => $e->requestor->id},
671 $hist_warning_needed = 1;
672 next; # no history updates while confirmation pending
677 $settings{$key} = undef;
679 if ($key eq 'history.circ.retention_start') {
680 # delete existing circulation history data.
683 'open-ils.actor.history.circ.clear',
684 $self->editor->authtoken);
689 # Warn patrons before clearing circ/hold history
690 if ($hist_warning_needed) {
691 $self->ctx->{clear_circ_history} = $clear_circ_history;
692 $self->ctx->{clear_hold_history} = $clear_hold_history;
693 $self->ctx->{confirm_history_delete} = 1;
696 # Send the modified settings off to be saved
699 'open-ils.actor.patron.settings.update',
700 $self->editor->authtoken, undef, \%settings);
702 # re-fetch user prefs
703 $self->ctx->{updated_user_settings} = \%settings;
704 return $self->_load_user_with_prefs || Apache2::Const::OK;
707 sub load_myopac_prefs_my_lists {
712 opac.list_items_per_page
715 my $stat = $self->_load_user_with_prefs;
716 return $stat if $stat;
718 return Apache2::Const::OK
719 unless $self->cgi->request_method eq 'POST';
722 my $set_map = $self->ctx->{user_setting_map};
724 foreach my $key (@user_prefs) {
725 my $val = $self->cgi->param($key);
726 $settings{$key}= $val unless $$set_map{$key} eq $val;
729 if (keys %settings) { # we found a different setting value
730 # Send the modified settings off to be saved
733 'open-ils.actor.patron.settings.update',
734 $self->editor->authtoken, undef, \%settings);
736 # re-fetch user prefs
737 $self->ctx->{updated_user_settings} = \%settings;
738 $stat = $self->_load_user_with_prefs;
741 return $stat || Apache2::Const::OK;
744 sub fetch_user_holds {
746 my $hold_ids = shift;
747 my $ids_only = shift;
749 my $available = shift;
753 my $e = $self->editor;
754 my $all_ids; # to be used below.
757 my $circ = OpenSRF::AppSession->create('open-ils.circ');
759 $hold_ids = $circ->request(
760 'open-ils.circ.holds.id_list.retrieve.authoritative',
767 $all_ids = $hold_ids;
768 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
771 $all_ids = $hold_ids;
774 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
777 suppress_notices => 1,
778 suppress_transits => 1,
780 suppress_patron_details => 1
783 # ----------------------------------------------------------------
784 # Collect holds in batches of $batch_size for faster retrieval
788 my $mk_req_batch = sub {
790 my $top_idx = $batch_idx + $batch_size;
791 while($batch_idx < $top_idx) {
792 my $hold_id = $hold_ids->[$batch_idx++];
793 last unless $hold_id;
794 my $ses = OpenSRF::AppSession->create('open-ils.circ');
795 my $req = $ses->request(
796 'open-ils.circ.hold.details.retrieve',
797 $e->authtoken, $hold_id, $args);
798 push(@ses, {ses => $ses, req => $req});
804 my(@collected, @holds, @ses);
807 @ses = $mk_req_batch->() if $first;
808 last if $first and not @ses;
811 while(my $blob = pop(@collected)) {
814 # in the holds edit UI, we need to know what formats and
815 # languages the user selected for this hold, plus what
816 # formats/langs are available on the MR as a whole.
817 if ($blob->{hold}{hold}->hold_type eq 'M') {
818 my $hold = $blob->{hold}->{hold};
820 # for MR, fetch the combined MR unapi blob
821 (undef, @data) = $self->get_records_and_facets(
822 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
824 my $filter_org = $U->org_unit_ancestor_at_depth(
826 $hold->selection_depth);
828 my $filter_data = $U->simplereq(
830 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
831 $hold->target, $filter_org, [$hold->id]
834 $blob->{metarecord_filters} =
835 $filter_data->[0]->{metarecord};
836 $blob->{metarecord_selected_filters} =
837 $filter_data->[1]->{hold};
840 (undef, @data) = $self->get_records_and_facets(
841 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
845 $blob->{marc_xml} = $data[0]->{marc_xml};
850 for my $req_data (@ses) {
851 push(@collected, {hold => $req_data->{req}->gather(1)});
852 $req_data->{ses}->kill_me;
855 @ses = $mk_req_batch->();
856 last unless @collected or @ses;
860 # put the holds back into the original server sort order
862 for my $id (@$hold_ids) {
863 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
866 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids };
869 sub handle_hold_update {
872 my $hold_ids = shift;
873 my $e = $self->editor;
876 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
877 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
879 my $circ = OpenSRF::AppSession->create('open-ils.circ');
881 if($action =~ /cancel/) {
883 for my $hold_id (@hold_ids) {
884 my $resp = $circ->request(
885 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
888 } elsif ($action =~ /activate|suspend/) {
891 for my $hold_id (@hold_ids) {
892 my $vals = {id => $hold_id};
894 if($action =~ /activate/) {
895 $vals->{frozen} = 'f';
896 $vals->{thaw_date} = undef;
898 } elsif($action =~ /suspend/) {
899 $vals->{frozen} = 't';
900 # $vals->{thaw_date} = TODO;
902 push(@$vlist, $vals);
905 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
906 $self->ctx->{hold_suspend_post_capture} = 1 if
907 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
909 } elsif ($action eq 'edit') {
912 my $val = {"id" => $_};
913 $val->{"frozen"} = $self->cgi->param("frozen");
914 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
916 for my $field (qw/expire_time thaw_date/) {
917 # XXX TODO make this support other date formats, not just
919 next unless $self->cgi->param($field) =~
920 m:^(\d{2})/(\d{2})/(\d{4})$:;
921 $val->{$field} = "$3-$1-$2";
924 $val->{holdable_formats} = # no-op for non-MR holds
925 $self->compile_holdable_formats(undef, $_);
931 'open-ils.circ.hold.update.batch.atomic',
932 $e->authtoken, undef, \@vals
933 )->gather(1); # LFW XXX test for failure
934 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
935 foreach my $param (('loc', 'qtype', 'query')) {
936 if ($self->cgi->param($param)) {
937 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
943 return defined($url) ? $self->generic_redirect($url) : undef;
946 sub load_myopac_holds {
948 my $e = $self->editor;
949 my $ctx = $self->ctx;
951 my $limit = $self->cgi->param('limit') || 15;
952 my $offset = $self->cgi->param('offset') || 0;
953 my $action = $self->cgi->param('action') || '';
954 my $hold_id = $self->cgi->param('hid');
955 my $available = int($self->cgi->param('available') || 0);
957 my $hold_handle_result;
958 $hold_handle_result = $self->handle_hold_update($action) if $action;
961 if ($self->cgi->param('sort') ne "") {
962 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
965 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
968 if($holds_object->{holds}) {
969 $ctx->{holds} = $holds_object->{holds};
971 $ctx->{holds_ids} = $holds_object->{all_ids};
972 $ctx->{holds_limit} = $limit;
973 $ctx->{holds_offset} = $offset;
975 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
980 sub load_place_hold {
982 my $ctx = $self->ctx;
983 my $gos = $ctx->{get_org_setting};
984 my $e = $self->editor;
985 my $cgi = $self->cgi;
987 $self->ctx->{page} = 'place_hold';
988 my @targets = uniq $cgi->param('hold_target');
989 my @parts = $cgi->param('part');
991 $ctx->{hold_type} = $cgi->param('hold_type');
992 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
993 $ctx->{email_notify} = $cgi->param('email_notify');
994 if ($cgi->param('phone_notify_checkbox')) {
995 $ctx->{phone_notify} = $cgi->param('phone_notify');
997 if ($cgi->param('sms_notify_checkbox')) {
998 $ctx->{sms_notify} = $cgi->param('sms_notify');
999 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1002 return $self->generic_redirect unless @targets;
1004 # Check for multiple hold placement via the num_copies widget.
1005 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1006 if ($num_copies > 1) {
1007 # Only if we have 1 hold target and no parts.
1008 if (scalar(@targets) == 1 && !$parts[0]) {
1009 # Also, only for M and T holds.
1010 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1011 # Add the extra holds to @targets. NOTE: We start with
1012 # 1 and go to < $num_copies to account for the
1014 for (my $i = 1; $i < $num_copies; $i++) {
1015 push(@targets, $targets[0]);
1021 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1023 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1028 au => ['settings', 'card']
1031 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1032 my $user_setting_map = {
1033 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1035 $ctx->{staff_recipient}->settings
1038 $ctx->{user_setting_map} = $user_setting_map;
1040 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1041 if ($default_notify =~ /email/) {
1042 $ctx->{default_email_notify} = 'checked';
1044 $ctx->{default_email_notify} = '';
1046 if ($default_notify =~ /phone/) {
1047 $ctx->{default_phone_notify} = 'checked';
1049 $ctx->{default_phone_notify} = '';
1051 if ($default_notify =~ /sms/) {
1052 $ctx->{default_sms_notify} = 'checked';
1054 $ctx->{default_sms_notify} = '';
1056 if ($cgi->param('hold_suspend')) {
1058 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1059 # We should use a date input type on the forms once it is supported by Firefox.
1060 # I didn't do that now because it is not available in a general release.
1061 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1063 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1064 $ctx->{thaw_date} = $dt->ymd;
1067 $logger->warn("ignoring invalid thaw_date when placing hold request");
1073 # If we have a default pickup location, grab it
1074 if ($$user_setting_map{'opac.default_pickup_location'}) {
1075 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1078 my $request_lib = $e->requestor->ws_ou;
1080 $ctx->{hold_data} = \@hold_data;
1082 $data_filler = sub {
1084 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1085 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1086 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1087 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1088 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1089 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1093 my $type_dispatch = {
1095 # target metarecords
1096 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1098 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1102 for my $id (@targets) {
1103 my ($mr) = grep {$_->id eq $id} @$mrecs;
1105 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1106 my $filter_data = $U->simplereq(
1108 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1110 my $holdable_formats =
1111 $self->compile_holdable_formats($mr->id);
1113 push(@hold_data, $data_filler->({
1115 record => $mr->master_record,
1116 holdable_formats => $holdable_formats,
1117 metarecord_filters => $filter_data->{metarecord}
1122 my $recs = $e->batch_retrieve_biblio_record_entry(
1123 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1127 for my $id (@targets) { # force back into the correct order
1128 my ($rec) = grep {$_->id eq $id} @$recs;
1130 # NOTE: if tpac ever supports locked-down pickup libs,
1131 # we'll need to pass a pickup_lib param along with the
1132 # record to filter the set of monographic parts.
1133 my $parts = $U->simplereq(
1135 'open-ils.search.biblio.record_hold_parts',
1136 {record => $rec->id}
1139 # T holds on records that have parts are OK, but if the record has
1140 # no non-part copies, the hold will ultimately fail. When that
1141 # happens, require the user to select a part.
1142 my $part_required = 0;
1144 my $np_copies = $e->json_query({
1145 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1146 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1148 '+acp' => {deleted => 'f'},
1149 '+acn' => {deleted => 'f', record => $rec->id},
1150 '+acpm' => {id => undef}
1153 $part_required = 1 if $np_copies->[0]->{count} == 0;
1156 push(@hold_data, $data_filler->({
1160 part_required => $part_required
1165 my $vols = $e->batch_retrieve_asset_call_number([
1168 "flesh_fields" => {"acn" => ["record"]}
1170 ], {substream => 1});
1172 for my $id (@targets) {
1173 my ($vol) = grep {$_->id eq $id} @$vols;
1174 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1178 my $copies = $e->batch_retrieve_asset_copy([
1182 "acn" => ["record"],
1183 "acp" => ["call_number"]
1186 ], {substream => 1});
1188 for my $id (@targets) {
1189 my ($copy) = grep {$_->id eq $id} @$copies;
1190 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1194 my $isses = $e->batch_retrieve_serial_issuance([
1198 "siss" => ["subscription"], "ssub" => ["record_entry"]
1201 ], {substream => 1});
1203 for my $id (@targets) {
1204 my ($iss) = grep {$_->id eq $id} @$isses;
1205 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1210 }->{$ctx->{hold_type}}->();
1212 # caller sent bad target IDs or the wrong hold type
1213 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1215 # generate the MARC xml for each record
1216 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1218 my $pickup_lib = $cgi->param('pickup_lib');
1219 # no pickup lib means no holds placement
1220 return Apache2::Const::OK unless $pickup_lib;
1222 $ctx->{hold_attempt_made} = 1;
1224 # Give the original CGI params back to the user in case they
1225 # want to try to override something.
1226 $ctx->{orig_params} = $cgi->Vars;
1227 delete $ctx->{orig_params}{submit};
1228 delete $ctx->{orig_params}{hold_target};
1229 delete $ctx->{orig_params}{part};
1231 my $usr = $e->requestor->id;
1233 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1234 # find the real hold target
1236 $usr = $U->simplereq(
1238 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1239 $e->authtoken, $cgi->param("hold_usr"));
1241 if (defined $U->event_code($usr)) {
1242 $ctx->{hold_failed} = 1;
1243 $ctx->{hold_failed_event} = $usr;
1247 # target_id is the true target_id for holds placement.
1248 # needed for attempt_hold_placement()
1249 # With the exception of P-type holds, target_id == target->id.
1250 $_->{target_id} = $_->{target}->id for @hold_data;
1252 if ($ctx->{hold_type} eq 'T') {
1254 # Much like quantum wave-particles, P-type holds pop into
1255 # and out of existence at the user's whim. For our purposes,
1256 # we treat such holds as T(itle) holds with a selected_part
1257 # designation. When the time comes to pass the hold information
1258 # off for holds possibility testing and placement, make it look
1259 # like a real P-type hold.
1260 my (@p_holds, @t_holds);
1262 # Now that we have the num_copies field for mutliple title and
1263 # metarecord hold placement, the number of holds and parts
1264 # arrays can get out of sync. We only want to parse out parts
1265 # if the numbers are equal.
1266 if ($#hold_data == $#parts) {
1267 for my $idx (0..$#parts) {
1268 my $hdata = $hold_data[$idx];
1269 if (my $part = $parts[$idx]) {
1270 $hdata->{target_id} = $part;
1271 $hdata->{selected_part} = $part;
1272 push(@p_holds, $hdata);
1274 push(@t_holds, $hdata);
1278 @t_holds = @hold_data;
1281 $self->apache->log->warn("$#parts : @t_holds");
1283 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1284 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1287 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1290 # NOTE: we are leaving the staff-placed patron barcode cookie
1291 # in place. Otherwise, it's not possible to place more than
1292 # one hold for the patron within a staff/patron session. This
1293 # does leave the barcode to linger longer than is ideal, but
1294 # normal staff work flow will cause the cookie to be replaced
1295 # with each new patron anyway.
1296 # TODO: See about getting the staff client to clear the cookie
1298 # return to the place_hold page so the results of the hold
1299 # placement attempt can be reported to the user
1300 return Apache2::Const::OK;
1303 sub attempt_hold_placement {
1304 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1305 my $cgi = $self->cgi;
1306 my $ctx = $self->ctx;
1307 my $e = $self->editor;
1309 # First see if we should warn/block for any holds that
1310 # might have locally available items.
1311 for my $hdata (@hold_data) {
1312 my ($local_block, $local_alert) = $self->local_avail_concern(
1313 $hdata->{target_id}, $hold_type, $pickup_lib);
1316 $hdata->{hold_failed} = 1;
1317 $hdata->{hold_local_block} = 1;
1318 } elsif ($local_alert) {
1319 $hdata->{hold_failed} = 1;
1320 $hdata->{hold_local_alert} = 1;
1324 my $method = 'open-ils.circ.holds.test_and_create.batch';
1326 if ($cgi->param('override')) {
1327 $method .= '.override';
1329 } elsif (!$ctx->{is_staff}) {
1331 $method .= '.override' if $self->ctx->{get_org_setting}->(
1332 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1335 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1338 if(@create_targets) {
1340 # holdable formats may be different for each MR hold.
1341 # map each set to the ID of the target.
1342 my $holdable_formats = {};
1343 if ($hold_type eq 'M') {
1344 $holdable_formats->{$_->{target_id}} =
1345 $_->{holdable_formats} for @hold_data;
1348 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1349 my $breq = $bses->request(
1354 pickup_lib => $pickup_lib,
1355 hold_type => $hold_type,
1356 holdable_formats_map => $holdable_formats,
1361 while (my $resp = $breq->recv) {
1363 $resp = $resp->content;
1364 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1366 if ($U->event_code($resp)) {
1367 $ctx->{general_hold_error} = $resp;
1371 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1372 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1373 my $result = $resp->{result};
1375 if ($U->event_code($result)) {
1376 # e.g. permission denied
1377 $hdata->{hold_failed} = 1;
1378 $hdata->{hold_failed_event} = $result;
1382 if(not ref $result and $result > 0) {
1383 # successul hold returns the hold ID
1385 $hdata->{hold_success} = $result;
1388 # hold-specific failure event
1389 $hdata->{hold_failed} = 1;
1391 if (ref $result eq 'HASH') {
1392 $hdata->{hold_failed_event} = $result->{last_event};
1394 if ($result->{age_protected_copy}) {
1395 my %temp = %{$hdata->{hold_failed_event}};
1396 my $theTextcode = $temp{"textcode"};
1397 $theTextcode.=".override";
1398 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1399 $hdata->{age_protect} = 1;
1401 $hdata->{could_override} = $result->{place_unfillable} ||
1402 $self->test_could_override($hdata->{hold_failed_event});
1404 } elsif (ref $result eq 'ARRAY') {
1405 $hdata->{hold_failed_event} = $result->[0];
1407 if ($result->[3]) { # age_protect_only
1408 my %temp = %{$hdata->{hold_failed_event}};
1409 my $theTextcode = $temp{"textcode"};
1410 $theTextcode.=".override";
1411 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1412 $hdata->{age_protect} = 1;
1414 $hdata->{could_override} = $result->[4] || # place_unfillable
1415 $self->test_could_override($hdata->{hold_failed_event});
1426 # pull the selected formats and languages for metarecord holds
1427 # from the CGI params and map them into the JSON holdable
1428 # formats...er, format.
1429 # if no metarecord is provided, we'll pull it from the target
1430 # of the provided hold.
1431 sub compile_holdable_formats {
1432 my ($self, $mr_id, $hold_id) = @_;
1433 my $e = $self->editor;
1434 my $cgi = $self->cgi;
1436 # exit early if not needed
1438 grep /metarecord_formats_|metarecord_langs_/,
1441 # CGI params are based on the MR id, since during hold placement
1442 # we have no old ID. During hold edit, map the hold ID back to
1443 # the metarecod target.
1445 $e->retrieve_action_hold_request($hold_id)->target
1448 my $format_attr = $self->ctx->{get_cgf}->(
1449 'opac.metarecord.holds.format_attr');
1451 if (!$format_attr) {
1452 $logger->error("Missing config.global_flag: ".
1453 "opac.metarecord.holds.format_attr!");
1457 $format_attr = $format_attr->value;
1459 # during hold placement or edit submission, the user selects
1460 # which of the available formats/langs are acceptable.
1461 # Capture those here as the holdable_formats for the MR hold.
1462 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1463 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1465 # map the selected attrs into the JSON holdable_formats structure
1467 if (@selected_formats) {
1469 map { {_attr => $format_attr, _val => $_} }
1473 if (@selected_langs) {
1475 map { {_attr => 'item_lang', _val => $_} }
1480 return OpenSRF::Utils::JSON->perl2JSON($blob);
1483 sub fetch_user_circs {
1485 my $flesh = shift; # flesh bib data, etc.
1486 my $circ_ids = shift;
1490 my $e = $self->editor;
1495 @circ_ids = @$circ_ids;
1500 select => {circ => ['id']},
1504 usr => $e->requestor->id,
1505 checkin_time => undef,
1507 {stop_fines => undef},
1508 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1512 order_by => {circ => ['due_date']}
1515 $query->{limit} = $limit if $limit;
1516 $query->{offset} = $offset if $offset;
1518 my $ids = $e->json_query($query);
1519 @circ_ids = map {$_->{id}} @$ids;
1522 return [] unless @circ_ids;
1527 circ => ['target_copy'],
1528 acp => ['call_number'],
1534 my $circs = $e->search_action_circulation(
1535 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1538 for my $circ (@$circs) {
1541 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1542 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1543 undef # pre-cat copy, use the dummy title/author instead
1548 # make sure the final list is in the correct order
1550 for my $id (@circ_ids) {
1553 (grep { $_->{circ}->id == $id } @circs)
1557 return \@sorted_circs;
1561 sub handle_circ_renew {
1564 my $ctx = $self->ctx;
1566 my @renew_ids = $self->cgi->param('circ');
1568 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1570 # TODO: fire off renewal calls in batches to speed things up
1572 for my $circ (@$circs) {
1574 my $evt = $U->simplereq(
1576 'open-ils.circ.renew',
1577 $self->editor->authtoken,
1579 patron_id => $self->editor->requestor->id,
1580 copy_id => $circ->{circ}->target_copy,
1585 # TODO return these, then insert them into the circ data
1586 # blob that is shoved into the template for each circ
1587 # so the template won't have to match them
1588 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1594 sub load_myopac_circs {
1596 my $e = $self->editor;
1597 my $ctx = $self->ctx;
1600 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1601 my $offset = $self->cgi->param('offset') || 0;
1602 my $action = $self->cgi->param('action') || '';
1604 # perform the renewal first if necessary
1605 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1607 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1609 my $success_renewals = 0;
1610 my $failed_renewals = 0;
1611 for my $data (@{$ctx->{circs}}) {
1612 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1615 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1617 # extract the fail_part, if present, from the event payload;
1618 # since # the payload is an acp object in some cases,
1619 # blindly looking for a # 'fail_part' key in the template can
1621 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
1622 $evt->{payload}->{fail_part} :
1625 $data->{renewal_response} = $evt;
1626 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1627 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1631 $ctx->{success_renewals} = $success_renewals;
1632 $ctx->{failed_renewals} = $failed_renewals;
1634 return Apache2::Const::OK;
1637 sub load_myopac_circ_history {
1639 my $e = $self->editor;
1640 my $ctx = $self->ctx;
1641 my $limit = $self->cgi->param('limit') || 15;
1642 my $offset = $self->cgi->param('offset') || 0;
1643 my $action = $self->cgi->param('action') || '';
1645 my $circ_handle_result;
1646 $circ_handle_result = $self->handle_circ_update($action) if $action;
1648 $ctx->{circ_history_limit} = $limit;
1649 $ctx->{circ_history_offset} = $offset;
1651 # Defer limitation to circ_history.tt2 when sorting
1652 if ($self->cgi->param('sort')) {
1657 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
1658 return Apache2::Const::OK;
1661 # if 'flesh' is set, copy data etc. is loaded and the return value is
1662 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
1664 sub fetch_user_circ_history {
1665 my ($self, $flesh, $limit, $offset) = @_;
1666 my $e = $self->editor;
1669 $limits{offset} = $offset if defined $offset;
1670 $limits{limit} = $limit if defined $limit;
1675 auch => ['target_copy','source_circ'],
1676 acp => ['call_number'],
1682 my $circs = $e->search_action_user_circ_history(
1684 {usr => $e->requestor->id},
1685 { # order newest to oldest by default
1686 order_by => {auch => 'xact_start DESC'},
1687 $flesh ? %flesh_ops : (),
1695 return $circs unless $flesh;
1699 my %unapi_cache = ();
1700 for my $circ (@$circs) {
1701 if ($circ->target_copy->call_number->id == -1) {
1704 marc_xml => undef # pre-cat copy, use the dummy title/author instead
1708 my $bre_id = $circ->target_copy->call_number->record->id;
1710 if (exists $unapi_cache{$bre_id}) {
1711 $unapi = $unapi_cache{$bre_id};
1713 my $result = $e->json_query({
1715 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
1719 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
1730 marc_xml => undef # failed, but try to go on
1739 sub handle_circ_update {
1742 my $circ_ids = shift;
1744 my $circ_ids //= [$self->cgi->param('circ_id')];
1746 if ($action =~ /delete/) {
1748 circ_ids => $circ_ids,
1753 'open-ils.actor.history.circ.clear',
1754 $self->editor->authtoken,
1762 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1763 sub load_myopac_hold_history {
1765 my $e = $self->editor;
1766 my $ctx = $self->ctx;
1767 my $limit = $self->cgi->param('limit') || 15;
1768 my $offset = $self->cgi->param('offset') || 0;
1769 $ctx->{hold_history_limit} = $limit;
1770 $ctx->{hold_history_offset} = $offset;
1772 my $hold_ids = $e->json_query({
1776 transform => 'action.usr_visible_holds',
1777 result_field => 'id'
1781 where => {id => $e->requestor->id}
1784 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1785 if($holds_object->{holds}) {
1786 $ctx->{holds} = $holds_object->{holds};
1788 $ctx->{hold_history_ids} = $holds_object->{all_ids};
1790 return Apache2::Const::OK;
1793 sub load_myopac_payment_form {
1797 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1798 $r = $self->prepare_extended_user_info and return $r;
1800 return Apache2::Const::OK;
1803 # TODO: add other filter options as params/configs/etc.
1804 sub load_myopac_payments {
1806 my $limit = $self->cgi->param('limit') || 20;
1807 my $offset = $self->cgi->param('offset') || 0;
1808 my $e = $self->editor;
1810 $self->ctx->{payment_history_limit} = $limit;
1811 $self->ctx->{payment_history_offset} = $offset;
1814 $args->{limit} = $limit if $limit;
1815 $args->{offset} = $offset if $offset;
1817 if (my $max_age = $self->ctx->{get_org_setting}->(
1818 $e->requestor->home_ou, "opac.payment_history_age_limit"
1820 my $min_ts = DateTime->now(
1821 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1822 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1824 $logger->info("XXX min_ts: $min_ts");
1825 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1828 $self->ctx->{payments} = $U->simplereq(
1830 'open-ils.actor.user.payments.retrieve.atomic',
1831 $e->authtoken, $e->requestor->id, $args);
1833 return Apache2::Const::OK;
1836 # 1. caches the form parameters
1837 # 2. loads the credit card payment "Processing..." page
1838 sub load_myopac_pay_init {
1840 my $cache = OpenSRF::Utils::Cache->new('global');
1842 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1844 if (!@payment_xacts) {
1845 # for consistency with load_myopac_payment_form() and
1846 # to preserve backwards compatibility, if no xacts are
1847 # selected, assume all (applicable) transactions are wanted.
1848 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1849 return $stat if $stat;
1851 map { $_->{xact}->id } (
1852 @{$self->ctx->{fines}->{circulation}},
1853 @{$self->ctx->{fines}->{grocery}}
1857 return $self->generic_redirect unless @payment_xacts;
1859 my $cc_args = {"where_process" => 1};
1861 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1862 number cvv2 expire_year expire_month billing_first
1863 billing_last billing_address billing_city billing_state
1864 billing_zip stripe_token
1868 cc_args => $cc_args,
1869 user => $self->ctx->{user}->id,
1870 xacts => \@payment_xacts
1873 # generate a temporary cache token and cache the form data
1874 my $token = md5_hex($$ . time() . rand());
1875 $cache->put_cache($token, $cache_args, 30);
1877 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1879 # after we render the processing page, we quickly redirect to submit
1880 # the actual payment. The refresh url contains the payment token.
1881 # It also contains the list of xact IDs, which allows us to clear the
1882 # cache at the earliest possible time while leaving a trace of which
1883 # transactions we were processing, so the UI can bring the user back
1884 # to the payment form w/ the same xacts if the payment fails.
1886 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1887 $refresh .= ";xact=$_" for @payment_xacts;
1888 $self->ctx->{refresh} = $refresh;
1890 return Apache2::Const::OK;
1893 # retrieve the cached CC payment info and send off for processing
1894 sub load_myopac_pay {
1896 my $token = $self->ctx->{page_args}->[0];
1897 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1899 my $cache = OpenSRF::Utils::Cache->new('global');
1900 my $cache_args = $cache->get_cache($token);
1901 $cache->delete_cache($token);
1903 # this page is loaded immediately after the token is created.
1904 # if the cached data is not there, it's because of an invalid
1905 # token (or cache failure) and not because of a timeout.
1906 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1908 my @payment_xacts = @{$cache_args->{xacts}};
1909 my $cc_args = $cache_args->{cc_args};
1911 # as an added security check, verify the user submitting
1912 # the form is the same as the user whose data was cached
1913 return Apache2::Const::HTTP_BAD_REQUEST unless
1914 $cache_args->{user} == $self->ctx->{user}->id;
1916 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1919 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1921 # balance_owed is computed specifically from the fines we're paying
1922 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1923 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1924 return Apache2::Const::HTTP_BAD_REQUEST;
1928 "cc_args" => $cc_args,
1929 "userid" => $self->ctx->{user}->id,
1930 "payment_type" => "credit_card_payment",
1931 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1934 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1935 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1938 $self->ctx->{"payment_response"} = $resp;
1940 unless ($resp->{"textcode"}) {
1941 $self->ctx->{printable_receipt} = $U->simplereq(
1942 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1943 $self->editor->authtoken, $resp->{payments}
1947 return Apache2::Const::OK;
1950 sub load_myopac_receipt_print {
1953 $self->ctx->{printable_receipt} = $U->simplereq(
1954 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1955 $self->editor->authtoken, [$self->cgi->param("payment")]
1958 return Apache2::Const::OK;
1961 sub load_myopac_receipt_email {
1964 # The following ML method doesn't actually check whether the user in
1965 # question has an email address, so we do.
1966 if ($self->ctx->{user}->email) {
1967 $self->ctx->{email_receipt_result} = $U->simplereq(
1968 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1969 $self->editor->authtoken, [$self->cgi->param("payment")]
1972 $self->ctx->{email_receipt_result} =
1973 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1976 return Apache2::Const::OK;
1980 my ($self, $limit, $offset, $id_list) = @_;
1982 # XXX TODO: check for failure after various network calls
1984 # It may be unclear, but this result structure lumps circulation and
1985 # reservation fines together, and keeps grocery fines separate.
1986 $self->ctx->{"fines"} = {
1987 "circulation" => [],
1994 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1996 # TODO: This should really be a ML call, but the existing calls
1997 # return an excessive amount of data and don't offer streaming
1999 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2001 my $req = $cstore->request(
2002 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2004 usr => $self->editor->requestor->id,
2005 balance_owed => {'!=' => 0},
2006 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2011 mobts => [qw/grocery circulation reservation/],
2012 bresv => ['target_resource_type'],
2016 circ => ['target_copy'],
2017 acp => ['call_number'],
2020 order_by => { mobts => 'xact_start' },
2025 # Collect $$ amounts from each transaction for summing below.
2026 my (@paid_amounts, @owed_amounts, @balance_amounts);
2028 while(my $resp = $req->recv) {
2029 my $mobts = $resp->content;
2030 my $circ = $mobts->circulation;
2033 if($mobts->grocery) {
2034 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2035 $last_billing = pop(@billings);
2038 push(@paid_amounts, $mobts->total_paid);
2039 push(@owed_amounts, $mobts->total_owed);
2040 push(@balance_amounts, $mobts->balance_owed);
2042 my $marc_xml = undef;
2043 if ($mobts->xact_type eq 'reservation' and
2044 $mobts->reservation->target_resource_type->record) {
2045 $marc_xml = XML::LibXML->new->parse_string(
2046 $mobts->reservation->target_resource_type->record->marc
2048 } elsif ($mobts->xact_type eq 'circulation' and
2049 $circ->target_copy->call_number->id != -1) {
2050 $marc_xml = XML::LibXML->new->parse_string(
2051 $circ->target_copy->call_number->record->marc
2056 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2059 last_grocery_billing => $last_billing,
2060 marc_xml => $marc_xml
2067 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2068 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2069 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2074 sub prepare_fines_for_payment {
2075 # This assumes $self->prepare_fines has already been run
2079 if ($self->ctx->{fines}) {
2080 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2081 @{$self->ctx->{fines}->{circulation}},
2082 @{$self->ctx->{fines}->{grocery}}
2089 sub load_myopac_main {
2091 my $limit = $self->cgi->param('limit') || 0;
2092 my $offset = $self->cgi->param('offset') || 0;
2093 $self->ctx->{search_ou} = $self->_get_search_lib();
2094 $self->ctx->{user}->notes(
2095 $self->editor->search_actor_usr_note({
2096 usr => $self->ctx->{user}->id,
2100 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2103 sub load_myopac_update_email {
2105 my $e = $self->editor;
2106 my $ctx = $self->ctx;
2107 my $email = $self->cgi->param('email') || '';
2108 my $current_pw = $self->cgi->param('current_pw') || '';
2110 # needed for most up-to-date email address
2111 if (my $r = $self->prepare_extended_user_info) { return $r };
2113 return Apache2::Const::OK
2114 unless $self->cgi->request_method eq 'POST';
2116 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2117 $ctx->{invalid_email} = $email;
2118 return Apache2::Const::OK;
2121 my $stat = $U->simplereq(
2123 'open-ils.actor.user.email.update',
2124 $e->authtoken, $email, $current_pw);
2126 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2127 $ctx->{password_incorrect} = 1;
2128 return Apache2::Const::OK;
2131 unless ($self->cgi->param("redirect_to")) {
2132 my $url = $self->apache->unparsed_uri;
2133 $url =~ s/update_email/prefs/;
2135 return $self->generic_redirect($url);
2138 return $self->generic_redirect;
2141 sub load_myopac_update_username {
2143 my $e = $self->editor;
2144 my $ctx = $self->ctx;
2145 my $username = $self->cgi->param('username') || '';
2146 my $current_pw = $self->cgi->param('current_pw') || '';
2148 $self->prepare_extended_user_info;
2150 my $allow_change = 1;
2152 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2153 if(defined($lock_usernames) and $lock_usernames == 1) {
2154 # Policy says no username changes
2157 # We want this further down.
2158 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2159 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2160 if(!$username_unlimit) {
2162 # Default is "starts with a number"
2163 $regex_check = '^\d+';
2165 # You already have a username?
2166 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2171 if(!$allow_change) {
2172 my $url = $self->apache->unparsed_uri;
2173 $url =~ s/update_username/prefs/;
2175 return $self->generic_redirect($url);
2178 return Apache2::Const::OK
2179 unless $self->cgi->request_method eq 'POST';
2181 unless($username and $username !~ /\s/) { # any other username restrictions?
2182 $ctx->{invalid_username} = $username;
2183 return Apache2::Const::OK;
2186 # New username can't look like a barcode if we have a barcode regex
2187 if($regex_check and $username =~ /$regex_check/) {
2188 $ctx->{invalid_username} = $username;
2189 return Apache2::Const::OK;
2192 # New username has to look like a username if we have a username regex
2193 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2194 if($regex_check and $username !~ /$regex_check/) {
2195 $ctx->{invalid_username} = $username;
2196 return Apache2::Const::OK;
2199 if($username ne $e->requestor->usrname) {
2201 my $evt = $U->simplereq(
2203 'open-ils.actor.user.username.update',
2204 $e->authtoken, $username, $current_pw);
2206 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2207 $ctx->{password_incorrect} = 1;
2208 return Apache2::Const::OK;
2211 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2212 $ctx->{username_exists} = $username;
2213 return Apache2::Const::OK;
2217 my $url = $self->apache->unparsed_uri;
2218 $url =~ s/update_username/prefs/;
2220 return $self->generic_redirect($url);
2223 sub load_myopac_update_password {
2225 my $e = $self->editor;
2226 my $ctx = $self->ctx;
2228 return Apache2::Const::OK
2229 unless $self->cgi->request_method eq 'POST';
2231 my $current_pw = $self->cgi->param('current_pw') || '';
2232 my $new_pw = $self->cgi->param('new_pw') || '';
2233 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2235 unless($new_pw eq $new_pw2) {
2236 $ctx->{password_nomatch} = 1;
2237 return Apache2::Const::OK;
2240 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2243 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2244 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2247 if($pw_regex and $new_pw !~ /$pw_regex/) {
2248 $ctx->{password_invalid} = 1;
2249 return Apache2::Const::OK;
2252 my $evt = $U->simplereq(
2254 'open-ils.actor.user.password.update',
2255 $e->authtoken, $new_pw, $current_pw);
2258 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2259 $ctx->{password_incorrect} = 1;
2260 return Apache2::Const::OK;
2263 my $url = $self->apache->unparsed_uri;
2264 $url =~ s/update_password/prefs/;
2266 return $self->generic_redirect($url);
2269 sub _update_bookbag_metadata {
2270 my ($self, $bookbag) = @_;
2272 $bookbag->name($self->cgi->param("name"));
2273 $bookbag->description($self->cgi->param("description"));
2275 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2279 sub _get_lists_per_page {
2282 if($self->editor->requestor) {
2283 $self->timelog("Checking for opac.lists_per_page preference");
2284 # See if the user has a lists per page preference
2285 my $ipp = $self->editor->search_actor_user_setting({
2286 usr => $self->editor->requestor->id,
2287 name => 'opac.lists_per_page'
2289 $self->timelog("Got opac.lists_per_page preference");
2290 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2292 return 10; # default
2295 sub _get_items_per_page {
2298 if($self->editor->requestor) {
2299 $self->timelog("Checking for opac.list_items_per_page preference");
2300 # See if the user has a list items per page preference
2301 my $ipp = $self->editor->search_actor_user_setting({
2302 usr => $self->editor->requestor->id,
2303 name => 'opac.list_items_per_page'
2305 $self->timelog("Got opac.list_items_per_page preference");
2306 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2308 return 10; # default
2311 sub load_myopac_bookbags {
2313 my $e = $self->editor;
2314 my $ctx = $self->ctx;
2315 my $limit = $self->_get_lists_per_page || 10;
2316 my $offset = $self->cgi->param('offset') || 0;
2318 $ctx->{bookbags_limit} = $limit;
2319 $ctx->{bookbags_offset} = $offset;
2321 # for list item pagination
2322 my $item_limit = $self->_get_items_per_page;
2323 my $item_page = $self->cgi->param('item_page') || 1;
2324 my $item_offset = ($item_page - 1) * $item_limit;
2325 $ctx->{bookbags_item_page} = $item_page;
2327 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2328 $e->xact_begin; # replication...
2330 my $rv = $self->load_mylist;
2331 unless($rv eq Apache2::Const::OK) {
2336 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2338 {owner => $e->requestor->id, btype => 'bookbag'}, {
2339 order_by => {cbreb => 'name'},
2347 if(!$ctx->{bookbags}) {
2349 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2352 # We load the user prefs to get their default bookbag.
2353 $self->_load_user_with_prefs;
2355 # We also want a total count of the user's bookbags.
2357 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2359 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2361 my $r = $e->json_query($q);
2362 $ctx->{bookbag_count} = $r->[0]->{'count'};
2364 # If the user wants a specific bookbag's items, load them.
2366 if ($self->cgi->param("bbid")) {
2368 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2371 my $query = $self->_prepare_bookbag_container_query(
2372 $bookbag->id, $sorter, $modifier
2375 # Calculate total count of the items in selected bookbag.
2376 # This total includes record entries that have no assets available.
2377 my $bb_search_results = $U->simplereq(
2378 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2379 {"limit" => 1, "offset" => 0}, $query
2380 ); # we only need the count, so do the actual search with limit=1
2382 if ($bb_search_results) {
2383 $ctx->{bb_item_count} = $bb_search_results->{count};
2385 $logger->warn("search failed in load_myopac_bookbags()");
2386 $ctx->{bb_item_count} = 0; # fallback value
2389 #calculate page count
2390 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2392 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2393 if (!$self->_update_bookbag_metadata($bookbag)) {
2395 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2398 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2401 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2402 if ($self->cgi->param($param)) {
2403 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
2407 return $self->generic_redirect($url);
2411 # we're done with our CStoreEditor. Rollback here so
2412 # later calls don't cause a timeout, resulting in a
2413 # transaction rollback under the covers.
2417 # For list items pagination
2419 "limit" => $item_limit,
2420 "offset" => $item_offset
2423 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2424 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2426 # capture pref_ou for callnumber filter/display
2427 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2429 # search for local callnumbers for display
2430 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2432 my (undef, @recs) = $self->get_records_and_facets(
2433 [ map {$_->target_biblio_record_entry->id} @$items ],
2436 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2438 site => $ctx->{get_aou}->($focus_ou)->shortname,
2439 pref_lib => $ctx->{pref_ou}
2443 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2445 $bookbag->items($items);
2449 # If we have add_rec, we got here from the "Add to new list"
2450 # or "See all" popmenu items.
2451 if (my $add_rec = $self->cgi->param('add_rec')) {
2452 $self->ctx->{add_rec} = $add_rec;
2453 # But not in the staff client, 'cause that breaks things.
2454 unless ($self->ctx->{is_staff}) {
2455 # allow caller to provide the where_from in cases where
2456 # the referer is an intermediate error page
2457 if ($self->cgi->param('where_from')) {
2458 $self->ctx->{where_from} = $self->cgi->param('where_from');
2460 $self->ctx->{where_from} = $self->ctx->{referer};
2461 if ( my $anchor = $self->cgi->param('anchor') ) {
2462 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2468 # this rollback may be a dupe, but that's OK because
2469 # cstoreditor ignores dupe rollbacks
2472 return Apache2::Const::OK;
2476 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
2477 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2478 sub load_myopac_bookbag_update {
2479 my ($self, $action, $list_id, @hold_recs) = @_;
2480 my $e = $self->editor;
2481 my $cgi = $self->cgi;
2483 # save_notes is effectively another action, but is passed in a separate
2484 # CGI parameter for what are really just layout reasons.
2485 $action = 'save_notes' if $cgi->param('save_notes');
2486 $action ||= $cgi->param('action');
2488 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2490 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2491 my @selected_item = $cgi->param('selected_item');
2492 my $shared = $cgi->param('shared');
2493 my $name = $cgi->param('name');
2494 my $description = $cgi->param('description');
2498 # This url intentionally leaves off the edit_notes parameter, but
2499 # may need to add some back in for paging.
2501 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2502 $self->ctx->{opac_root} . "/myopac/lists?";
2504 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2505 if ($cgi->param($param)) {
2506 $url .= "$param=" . uri_escape_utf8($cgi->param($param)) . ";";
2510 if ($action eq 'create') {
2513 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2515 $list->description($description);
2516 $list->owner($e->requestor->id);
2517 $list->btype('bookbag');
2518 $list->pub($shared ? 't' : 'f');
2519 $success = $U->simplereq('open-ils.actor',
2520 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2521 if (ref($success) ne 'HASH' && scalar @add_rec) {
2522 $list_id = (ref($success)) ? $success->id : $success;
2523 foreach my $add_rec (@add_rec) {
2524 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2525 $item->bucket($list_id);
2526 $item->target_biblio_record_entry($add_rec);
2527 $success = $U->simplereq('open-ils.actor',
2528 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2529 last unless $success;
2532 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
2535 $self->ctx->{bucket_failure_noname} = 1;
2538 } elsif($action eq 'place_hold') {
2540 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
2541 unless (@hold_recs) {
2542 if (@selected_item) {
2543 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
2544 @hold_recs = map { $_->target_biblio_record_entry } @$items;
2548 return Apache2::Const::OK unless @hold_recs;
2549 $logger->info("placing holds from list page on: @hold_recs");
2551 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
2552 $url .= ';hold_target=' . $_ for @hold_recs;
2553 foreach my $param (('loc', 'qtype', 'query')) {
2554 if ($cgi->param($param)) {
2555 $url .= ";$param=" . uri_escape_utf8($cgi->param($param));
2558 return $self->generic_redirect($url);
2562 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
2564 return Apache2::Const::HTTP_BAD_REQUEST unless
2565 $list and $list->owner == $e->requestor->id;
2568 if($action eq 'delete') {
2569 $success = $U->simplereq('open-ils.actor',
2570 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
2572 # We check to see if we're deleting the user's default list.
2573 $self->_load_user_with_prefs;
2574 my $settings_map = $self->ctx->{user_setting_map};
2575 if ($$settings_map{'opac.default_list'} == $list_id) {
2576 # We unset the user's opac.default_list setting.
2577 $success = $U->simplereq(
2579 'open-ils.actor.patron.settings.update',
2582 { 'opac.default_list' => 0 }
2586 } elsif($action eq 'show') {
2587 unless($U->is_true($list->pub)) {
2589 $success = $U->simplereq('open-ils.actor',
2590 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2593 } elsif($action eq 'hide') {
2594 if($U->is_true($list->pub)) {
2596 $success = $U->simplereq('open-ils.actor',
2597 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2600 } elsif($action eq 'rename') {
2603 $success = $U->simplereq('open-ils.actor',
2604 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2607 } elsif($action eq 'add_rec') {
2608 foreach my $add_rec (@add_rec) {
2609 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2610 $item->bucket($list_id);
2611 $item->target_biblio_record_entry($add_rec);
2612 $success = $U->simplereq('open-ils.actor',
2613 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2614 last unless $success;
2616 # Redirect back where we came from if we have an anchor parameter:
2617 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
2618 $url = $self->ctx->{referer};
2619 $url =~ s/#.*|$/#$anchor/;
2620 } elsif ($cgi->param('where_from')) {
2621 # Or, if we have a "where_from" parameter.
2622 $url = $cgi->param('where_from');
2624 } elsif ($action eq 'del_item') {
2625 foreach (@selected_item) {
2626 $success = $U->simplereq(
2628 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
2630 last unless $success;
2632 } elsif ($action eq 'save_notes') {
2633 $success = $self->update_bookbag_item_notes;
2634 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
2635 } elsif ($action eq 'make_default') {
2636 $success = $U->simplereq(
2638 'open-ils.actor.patron.settings.update',
2641 { 'opac.default_list' => $list_id }
2643 } elsif ($action eq 'remove_default') {
2644 $success = $U->simplereq(
2646 'open-ils.actor.patron.settings.update',
2649 { 'opac.default_list' => 0 }
2653 return $self->generic_redirect($url) if $success;
2655 $self->ctx->{where_from} = $cgi->param('where_from');
2656 $self->ctx->{bucket_action} = $action;
2657 $self->ctx->{bucket_action_failed} = 1;
2658 return Apache2::Const::OK;
2661 sub update_bookbag_item_notes {
2663 my $e = $self->editor;
2665 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2666 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2668 # We're going to leverage an API call that's already been written to check
2669 # permissions appropriately.
2671 my $a = create OpenSRF::AppSession("open-ils.actor");
2672 my $method = "open-ils.actor.container.item_note.cud";
2674 for my $note_key (@note_keys) {
2677 my $id = ($note_key =~ /(\d+)/)[0];
2680 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2681 my $event = $e->die_event;
2682 $self->apache->log->warn(
2683 "error retrieving cbrebin id $id, got event " .
2687 $self->ctx->{bucket_action_event} = $event;
2691 if (length($self->cgi->param($note_key))) {
2692 $note->ischanged(1);
2693 $note->note($self->cgi->param($note_key));
2695 $note->isdeleted(1);
2698 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2700 if (defined $U->event_code($r)) {
2701 $self->apache->log->warn(
2702 "attempt to modify cbrebin " . $note->id .
2703 " returned event " . $r->{textcode}
2707 $self->ctx->{bucket_action_event} = $r;
2712 for my $item_key (@item_keys) {
2713 my $id = int(($item_key =~ /(\d+)/)[0]);
2714 my $text = $self->cgi->param($item_key);
2717 next unless length $text;
2719 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2724 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2726 if (defined $U->event_code($r)) {
2727 $self->apache->log->warn(
2728 "attempt to create cbrebin for item " . $note->item .
2729 " returned event " . $r->{textcode}
2733 $self->ctx->{bucket_action_event} = $r;
2742 sub load_myopac_bookbag_print {
2745 my $id = int($self->cgi->param("list"));
2747 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2750 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2754 # Get the bookbag object itself, assuming we're allowed to.
2755 if ($self->editor->allowed("VIEW_CONTAINER")) {
2757 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2759 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2763 "owner" => $self->editor->requestor->id,
2767 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2769 $bbag = pop @$bookbags;
2772 # If we have a bookbag we're allowed to look at, issue the A/T event
2773 # to get CSV, passing as a user param that search query we built before.
2775 $self->ctx->{csv} = $U->fire_object_event(
2776 undef, "container.biblio_record_entry_bucket.csv",
2777 $bbag, $self->editor->requestor->home_ou,
2778 undef, {"item_search" => $item_search}
2782 # Create a reasonable filename and set the content disposition to
2783 # provoke browser download dialogs.
2784 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2786 return $self->set_file_download_headers("$filename.csv");
2789 sub load_myopac_circ_history_export {
2791 my $e = $self->editor;
2792 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2794 my $circs = $self->fetch_user_circ_history(1);
2796 $self->ctx->{csv}->{circs} = $circs;
2797 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
2801 sub load_password_reset {
2803 my $cgi = $self->cgi;
2804 my $ctx = $self->ctx;
2805 my $barcode = $cgi->param('barcode');
2806 my $username = $cgi->param('username');
2807 my $email = $cgi->param('email');
2808 my $pwd1 = $cgi->param('pwd1');
2809 my $pwd2 = $cgi->param('pwd2');
2810 my $uuid = $ctx->{page_args}->[0];
2814 $logger->info("patron password reset with uuid $uuid");
2816 if ($pwd1 and $pwd2) {
2818 if ($pwd1 eq $pwd2) {
2820 my $response = $U->simplereq(
2822 'open-ils.actor.patron.password_reset.commit',
2825 $logger->info("patron password reset response " . Dumper($response));
2827 if ($U->event_code($response)) { # non-success event
2829 my $code = $response->{textcode};
2831 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2832 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2835 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2836 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2841 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2844 } else { # passwords not equal
2846 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2849 } else { # 2 password values needed
2851 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2854 } elsif ($barcode or $username) {
2856 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2857 push(@params, $email) if $email;
2861 'open-ils.actor.patron.password_reset.request', @params);
2863 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2866 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2867 return Apache2::Const::OK;