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 my @vals = $self->cgi->param($param);
938 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
944 return defined($url) ? $self->generic_redirect($url) : undef;
947 sub load_myopac_holds {
949 my $e = $self->editor;
950 my $ctx = $self->ctx;
952 my $limit = $self->cgi->param('limit') || 15;
953 my $offset = $self->cgi->param('offset') || 0;
954 my $action = $self->cgi->param('action') || '';
955 my $hold_id = $self->cgi->param('hid');
956 my $available = int($self->cgi->param('available') || 0);
958 my $hold_handle_result;
959 $hold_handle_result = $self->handle_hold_update($action) if $action;
962 if ($self->cgi->param('sort') ne "") {
963 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
966 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
969 if($holds_object->{holds}) {
970 $ctx->{holds} = $holds_object->{holds};
972 $ctx->{holds_ids} = $holds_object->{all_ids};
973 $ctx->{holds_limit} = $limit;
974 $ctx->{holds_offset} = $offset;
976 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
981 sub load_place_hold {
983 my $ctx = $self->ctx;
984 my $gos = $ctx->{get_org_setting};
985 my $e = $self->editor;
986 my $cgi = $self->cgi;
988 $self->ctx->{page} = 'place_hold';
989 my @targets = uniq $cgi->param('hold_target');
990 my @parts = $cgi->param('part');
992 $ctx->{hold_type} = $cgi->param('hold_type');
993 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
994 $ctx->{email_notify} = $cgi->param('email_notify');
995 if ($cgi->param('phone_notify_checkbox')) {
996 $ctx->{phone_notify} = $cgi->param('phone_notify');
998 if ($cgi->param('sms_notify_checkbox')) {
999 $ctx->{sms_notify} = $cgi->param('sms_notify');
1000 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1003 return $self->generic_redirect unless @targets;
1005 # Check for multiple hold placement via the num_copies widget.
1006 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1007 if ($num_copies > 1) {
1008 # Only if we have 1 hold target and no parts.
1009 if (scalar(@targets) == 1 && !$parts[0]) {
1010 # Also, only for M and T holds.
1011 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1012 # Add the extra holds to @targets. NOTE: We start with
1013 # 1 and go to < $num_copies to account for the
1015 for (my $i = 1; $i < $num_copies; $i++) {
1016 push(@targets, $targets[0]);
1022 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1024 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1029 au => ['settings', 'card']
1032 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1033 my $user_setting_map = {
1034 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1036 $ctx->{staff_recipient}->settings
1039 $ctx->{user_setting_map} = $user_setting_map;
1041 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1042 if ($default_notify =~ /email/) {
1043 $ctx->{default_email_notify} = 'checked';
1045 $ctx->{default_email_notify} = '';
1047 if ($default_notify =~ /phone/) {
1048 $ctx->{default_phone_notify} = 'checked';
1050 $ctx->{default_phone_notify} = '';
1052 if ($default_notify =~ /sms/) {
1053 $ctx->{default_sms_notify} = 'checked';
1055 $ctx->{default_sms_notify} = '';
1057 if ($cgi->param('hold_suspend')) {
1059 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1060 # We should use a date input type on the forms once it is supported by Firefox.
1061 # I didn't do that now because it is not available in a general release.
1062 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1064 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1065 $ctx->{thaw_date} = $dt->ymd;
1068 $logger->warn("ignoring invalid thaw_date when placing hold request");
1074 # If we have a default pickup location, grab it
1075 if ($$user_setting_map{'opac.default_pickup_location'}) {
1076 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1079 my $request_lib = $e->requestor->ws_ou;
1081 $ctx->{hold_data} = \@hold_data;
1083 $data_filler = sub {
1085 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1086 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1087 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1088 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1089 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1090 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1094 my $type_dispatch = {
1096 # target metarecords
1097 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1099 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1103 for my $id (@targets) {
1104 my ($mr) = grep {$_->id eq $id} @$mrecs;
1106 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1107 my $filter_data = $U->simplereq(
1109 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1111 my $holdable_formats =
1112 $self->compile_holdable_formats($mr->id);
1114 push(@hold_data, $data_filler->({
1116 record => $mr->master_record,
1117 holdable_formats => $holdable_formats,
1118 metarecord_filters => $filter_data->{metarecord}
1123 my $recs = $e->batch_retrieve_biblio_record_entry(
1124 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1128 for my $id (@targets) { # force back into the correct order
1129 my ($rec) = grep {$_->id eq $id} @$recs;
1131 # NOTE: if tpac ever supports locked-down pickup libs,
1132 # we'll need to pass a pickup_lib param along with the
1133 # record to filter the set of monographic parts.
1134 my $parts = $U->simplereq(
1136 'open-ils.search.biblio.record_hold_parts',
1137 {record => $rec->id}
1140 # T holds on records that have parts are OK, but if the record has
1141 # no non-part copies, the hold will ultimately fail. When that
1142 # happens, require the user to select a part.
1143 my $part_required = 0;
1145 my $np_copies = $e->json_query({
1146 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1147 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1149 '+acp' => {deleted => 'f'},
1150 '+acn' => {deleted => 'f', record => $rec->id},
1151 '+acpm' => {id => undef}
1154 $part_required = 1 if $np_copies->[0]->{count} == 0;
1157 push(@hold_data, $data_filler->({
1161 part_required => $part_required
1166 my $vols = $e->batch_retrieve_asset_call_number([
1169 "flesh_fields" => {"acn" => ["record"]}
1171 ], {substream => 1});
1173 for my $id (@targets) {
1174 my ($vol) = grep {$_->id eq $id} @$vols;
1175 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1179 my $copies = $e->batch_retrieve_asset_copy([
1183 "acn" => ["record"],
1184 "acp" => ["call_number"]
1187 ], {substream => 1});
1189 for my $id (@targets) {
1190 my ($copy) = grep {$_->id eq $id} @$copies;
1191 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1195 my $isses = $e->batch_retrieve_serial_issuance([
1199 "siss" => ["subscription"], "ssub" => ["record_entry"]
1202 ], {substream => 1});
1204 for my $id (@targets) {
1205 my ($iss) = grep {$_->id eq $id} @$isses;
1206 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1211 }->{$ctx->{hold_type}}->();
1213 # caller sent bad target IDs or the wrong hold type
1214 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1216 # generate the MARC xml for each record
1217 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1219 my $pickup_lib = $cgi->param('pickup_lib');
1220 # no pickup lib means no holds placement
1221 return Apache2::Const::OK unless $pickup_lib;
1223 $ctx->{hold_attempt_made} = 1;
1225 # Give the original CGI params back to the user in case they
1226 # want to try to override something.
1227 $ctx->{orig_params} = $cgi->Vars;
1228 delete $ctx->{orig_params}{submit};
1229 delete $ctx->{orig_params}{hold_target};
1230 delete $ctx->{orig_params}{part};
1232 my $usr = $e->requestor->id;
1234 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1235 # find the real hold target
1237 $usr = $U->simplereq(
1239 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1240 $e->authtoken, $cgi->param("hold_usr"));
1242 if (defined $U->event_code($usr)) {
1243 $ctx->{hold_failed} = 1;
1244 $ctx->{hold_failed_event} = $usr;
1248 # target_id is the true target_id for holds placement.
1249 # needed for attempt_hold_placement()
1250 # With the exception of P-type holds, target_id == target->id.
1251 $_->{target_id} = $_->{target}->id for @hold_data;
1253 if ($ctx->{hold_type} eq 'T') {
1255 # Much like quantum wave-particles, P-type holds pop into
1256 # and out of existence at the user's whim. For our purposes,
1257 # we treat such holds as T(itle) holds with a selected_part
1258 # designation. When the time comes to pass the hold information
1259 # off for holds possibility testing and placement, make it look
1260 # like a real P-type hold.
1261 my (@p_holds, @t_holds);
1263 # Now that we have the num_copies field for mutliple title and
1264 # metarecord hold placement, the number of holds and parts
1265 # arrays can get out of sync. We only want to parse out parts
1266 # if the numbers are equal.
1267 if ($#hold_data == $#parts) {
1268 for my $idx (0..$#parts) {
1269 my $hdata = $hold_data[$idx];
1270 if (my $part = $parts[$idx]) {
1271 $hdata->{target_id} = $part;
1272 $hdata->{selected_part} = $part;
1273 push(@p_holds, $hdata);
1275 push(@t_holds, $hdata);
1279 @t_holds = @hold_data;
1282 $self->apache->log->warn("$#parts : @t_holds");
1284 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1285 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1288 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1291 # NOTE: we are leaving the staff-placed patron barcode cookie
1292 # in place. Otherwise, it's not possible to place more than
1293 # one hold for the patron within a staff/patron session. This
1294 # does leave the barcode to linger longer than is ideal, but
1295 # normal staff work flow will cause the cookie to be replaced
1296 # with each new patron anyway.
1297 # TODO: See about getting the staff client to clear the cookie
1299 # return to the place_hold page so the results of the hold
1300 # placement attempt can be reported to the user
1301 return Apache2::Const::OK;
1304 sub attempt_hold_placement {
1305 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1306 my $cgi = $self->cgi;
1307 my $ctx = $self->ctx;
1308 my $e = $self->editor;
1310 # First see if we should warn/block for any holds that
1311 # might have locally available items.
1312 for my $hdata (@hold_data) {
1313 my ($local_block, $local_alert) = $self->local_avail_concern(
1314 $hdata->{target_id}, $hold_type, $pickup_lib);
1317 $hdata->{hold_failed} = 1;
1318 $hdata->{hold_local_block} = 1;
1319 } elsif ($local_alert) {
1320 $hdata->{hold_failed} = 1;
1321 $hdata->{hold_local_alert} = 1;
1325 my $method = 'open-ils.circ.holds.test_and_create.batch';
1327 if ($cgi->param('override')) {
1328 $method .= '.override';
1330 } elsif (!$ctx->{is_staff}) {
1332 $method .= '.override' if $self->ctx->{get_org_setting}->(
1333 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1336 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1339 if(@create_targets) {
1341 # holdable formats may be different for each MR hold.
1342 # map each set to the ID of the target.
1343 my $holdable_formats = {};
1344 if ($hold_type eq 'M') {
1345 $holdable_formats->{$_->{target_id}} =
1346 $_->{holdable_formats} for @hold_data;
1349 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1350 my $breq = $bses->request(
1355 pickup_lib => $pickup_lib,
1356 hold_type => $hold_type,
1357 holdable_formats_map => $holdable_formats,
1362 while (my $resp = $breq->recv) {
1364 $resp = $resp->content;
1365 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1367 if ($U->event_code($resp)) {
1368 $ctx->{general_hold_error} = $resp;
1372 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1373 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1374 my $result = $resp->{result};
1376 if ($U->event_code($result)) {
1377 # e.g. permission denied
1378 $hdata->{hold_failed} = 1;
1379 $hdata->{hold_failed_event} = $result;
1383 if(not ref $result and $result > 0) {
1384 # successul hold returns the hold ID
1386 $hdata->{hold_success} = $result;
1389 # hold-specific failure event
1390 $hdata->{hold_failed} = 1;
1392 if (ref $result eq 'HASH') {
1393 $hdata->{hold_failed_event} = $result->{last_event};
1395 if ($result->{age_protected_copy}) {
1396 my %temp = %{$hdata->{hold_failed_event}};
1397 my $theTextcode = $temp{"textcode"};
1398 $theTextcode.=".override";
1399 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1400 $hdata->{age_protect} = 1;
1402 $hdata->{could_override} = $result->{place_unfillable} ||
1403 $self->test_could_override($hdata->{hold_failed_event});
1405 } elsif (ref $result eq 'ARRAY') {
1406 $hdata->{hold_failed_event} = $result->[0];
1408 if ($result->[3]) { # age_protect_only
1409 my %temp = %{$hdata->{hold_failed_event}};
1410 my $theTextcode = $temp{"textcode"};
1411 $theTextcode.=".override";
1412 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1413 $hdata->{age_protect} = 1;
1415 $hdata->{could_override} = $result->[4] || # place_unfillable
1416 $self->test_could_override($hdata->{hold_failed_event});
1426 if ($self->cgi->param('clear_cart')) {
1427 $self->clear_anon_cache;
1431 # pull the selected formats and languages for metarecord holds
1432 # from the CGI params and map them into the JSON holdable
1433 # formats...er, format.
1434 # if no metarecord is provided, we'll pull it from the target
1435 # of the provided hold.
1436 sub compile_holdable_formats {
1437 my ($self, $mr_id, $hold_id) = @_;
1438 my $e = $self->editor;
1439 my $cgi = $self->cgi;
1441 # exit early if not needed
1443 grep /metarecord_formats_|metarecord_langs_/,
1446 # CGI params are based on the MR id, since during hold placement
1447 # we have no old ID. During hold edit, map the hold ID back to
1448 # the metarecod target.
1450 $e->retrieve_action_hold_request($hold_id)->target
1453 my $format_attr = $self->ctx->{get_cgf}->(
1454 'opac.metarecord.holds.format_attr');
1456 if (!$format_attr) {
1457 $logger->error("Missing config.global_flag: ".
1458 "opac.metarecord.holds.format_attr!");
1462 $format_attr = $format_attr->value;
1464 # during hold placement or edit submission, the user selects
1465 # which of the available formats/langs are acceptable.
1466 # Capture those here as the holdable_formats for the MR hold.
1467 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1468 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1470 # map the selected attrs into the JSON holdable_formats structure
1472 if (@selected_formats) {
1474 map { {_attr => $format_attr, _val => $_} }
1478 if (@selected_langs) {
1480 map { {_attr => 'item_lang', _val => $_} }
1485 return OpenSRF::Utils::JSON->perl2JSON($blob);
1488 sub fetch_user_circs {
1490 my $flesh = shift; # flesh bib data, etc.
1491 my $circ_ids = shift;
1495 my $e = $self->editor;
1500 @circ_ids = @$circ_ids;
1505 select => {circ => ['id']},
1509 usr => $e->requestor->id,
1510 checkin_time => undef,
1512 {stop_fines => undef},
1513 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1517 order_by => {circ => ['due_date']}
1520 $query->{limit} = $limit if $limit;
1521 $query->{offset} = $offset if $offset;
1523 my $ids = $e->json_query($query);
1524 @circ_ids = map {$_->{id}} @$ids;
1527 return [] unless @circ_ids;
1532 circ => ['target_copy'],
1533 acp => ['call_number'],
1539 my $circs = $e->search_action_circulation(
1540 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1543 for my $circ (@$circs) {
1546 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1547 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1548 undef # pre-cat copy, use the dummy title/author instead
1553 # make sure the final list is in the correct order
1555 for my $id (@circ_ids) {
1558 (grep { $_->{circ}->id == $id } @circs)
1562 return \@sorted_circs;
1566 sub handle_circ_renew {
1569 my $ctx = $self->ctx;
1571 my @renew_ids = $self->cgi->param('circ');
1573 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1575 # TODO: fire off renewal calls in batches to speed things up
1577 for my $circ (@$circs) {
1579 my $evt = $U->simplereq(
1581 'open-ils.circ.renew',
1582 $self->editor->authtoken,
1584 patron_id => $self->editor->requestor->id,
1585 copy_id => $circ->{circ}->target_copy,
1590 # TODO return these, then insert them into the circ data
1591 # blob that is shoved into the template for each circ
1592 # so the template won't have to match them
1593 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1599 sub load_myopac_circs {
1601 my $e = $self->editor;
1602 my $ctx = $self->ctx;
1605 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1606 my $offset = $self->cgi->param('offset') || 0;
1607 my $action = $self->cgi->param('action') || '';
1609 # perform the renewal first if necessary
1610 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1612 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1614 my $success_renewals = 0;
1615 my $failed_renewals = 0;
1616 for my $data (@{$ctx->{circs}}) {
1617 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1620 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1622 # extract the fail_part, if present, from the event payload;
1623 # since # the payload is an acp object in some cases,
1624 # blindly looking for a # 'fail_part' key in the template can
1626 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
1627 $evt->{payload}->{fail_part} :
1630 $data->{renewal_response} = $evt;
1631 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1632 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1636 $ctx->{success_renewals} = $success_renewals;
1637 $ctx->{failed_renewals} = $failed_renewals;
1639 return Apache2::Const::OK;
1642 sub load_myopac_circ_history {
1644 my $e = $self->editor;
1645 my $ctx = $self->ctx;
1646 my $limit = $self->cgi->param('limit') || 15;
1647 my $offset = $self->cgi->param('offset') || 0;
1648 my $action = $self->cgi->param('action') || '';
1650 my $circ_handle_result;
1651 $circ_handle_result = $self->handle_circ_update($action) if $action;
1653 $ctx->{circ_history_limit} = $limit;
1654 $ctx->{circ_history_offset} = $offset;
1656 # Defer limitation to circ_history.tt2 when sorting
1657 if ($self->cgi->param('sort')) {
1662 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
1663 return Apache2::Const::OK;
1666 # if 'flesh' is set, copy data etc. is loaded and the return value is
1667 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
1669 sub fetch_user_circ_history {
1670 my ($self, $flesh, $limit, $offset) = @_;
1671 my $e = $self->editor;
1674 $limits{offset} = $offset if defined $offset;
1675 $limits{limit} = $limit if defined $limit;
1680 auch => ['target_copy','source_circ'],
1681 acp => ['call_number'],
1687 my $circs = $e->search_action_user_circ_history(
1689 {usr => $e->requestor->id},
1690 { # order newest to oldest by default
1691 order_by => {auch => 'xact_start DESC'},
1692 $flesh ? %flesh_ops : (),
1700 return $circs unless $flesh;
1704 my %unapi_cache = ();
1705 for my $circ (@$circs) {
1706 if ($circ->target_copy->call_number->id == -1) {
1709 marc_xml => undef # pre-cat copy, use the dummy title/author instead
1713 my $bre_id = $circ->target_copy->call_number->record->id;
1715 if (exists $unapi_cache{$bre_id}) {
1716 $unapi = $unapi_cache{$bre_id};
1718 my $result = $e->json_query({
1720 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
1724 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
1735 marc_xml => undef # failed, but try to go on
1744 sub handle_circ_update {
1747 my $circ_ids = shift;
1749 my $circ_ids //= [$self->cgi->param('circ_id')];
1751 if ($action =~ /delete/) {
1753 circ_ids => $circ_ids,
1758 'open-ils.actor.history.circ.clear',
1759 $self->editor->authtoken,
1767 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1768 sub load_myopac_hold_history {
1770 my $e = $self->editor;
1771 my $ctx = $self->ctx;
1772 my $limit = $self->cgi->param('limit') || 15;
1773 my $offset = $self->cgi->param('offset') || 0;
1774 $ctx->{hold_history_limit} = $limit;
1775 $ctx->{hold_history_offset} = $offset;
1777 my $hold_ids = $e->json_query({
1781 transform => 'action.usr_visible_holds',
1782 result_field => 'id'
1786 where => {id => $e->requestor->id}
1789 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1790 if($holds_object->{holds}) {
1791 $ctx->{holds} = $holds_object->{holds};
1793 $ctx->{hold_history_ids} = $holds_object->{all_ids};
1795 return Apache2::Const::OK;
1798 sub load_myopac_payment_form {
1802 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1803 $r = $self->prepare_extended_user_info and return $r;
1805 return Apache2::Const::OK;
1808 # TODO: add other filter options as params/configs/etc.
1809 sub load_myopac_payments {
1811 my $limit = $self->cgi->param('limit') || 20;
1812 my $offset = $self->cgi->param('offset') || 0;
1813 my $e = $self->editor;
1815 $self->ctx->{payment_history_limit} = $limit;
1816 $self->ctx->{payment_history_offset} = $offset;
1819 $args->{limit} = $limit if $limit;
1820 $args->{offset} = $offset if $offset;
1822 if (my $max_age = $self->ctx->{get_org_setting}->(
1823 $e->requestor->home_ou, "opac.payment_history_age_limit"
1825 my $min_ts = DateTime->now(
1826 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1827 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1829 $logger->info("XXX min_ts: $min_ts");
1830 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1833 $self->ctx->{payments} = $U->simplereq(
1835 'open-ils.actor.user.payments.retrieve.atomic',
1836 $e->authtoken, $e->requestor->id, $args);
1838 return Apache2::Const::OK;
1841 # 1. caches the form parameters
1842 # 2. loads the credit card payment "Processing..." page
1843 sub load_myopac_pay_init {
1845 my $cache = OpenSRF::Utils::Cache->new('global');
1847 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1849 if (!@payment_xacts) {
1850 # for consistency with load_myopac_payment_form() and
1851 # to preserve backwards compatibility, if no xacts are
1852 # selected, assume all (applicable) transactions are wanted.
1853 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1854 return $stat if $stat;
1856 map { $_->{xact}->id } (
1857 @{$self->ctx->{fines}->{circulation}},
1858 @{$self->ctx->{fines}->{grocery}}
1862 return $self->generic_redirect unless @payment_xacts;
1864 my $cc_args = {"where_process" => 1};
1866 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1867 number cvv2 expire_year expire_month billing_first
1868 billing_last billing_address billing_city billing_state
1869 billing_zip stripe_token
1873 cc_args => $cc_args,
1874 user => $self->ctx->{user}->id,
1875 xacts => \@payment_xacts
1878 # generate a temporary cache token and cache the form data
1879 my $token = md5_hex($$ . time() . rand());
1880 $cache->put_cache($token, $cache_args, 30);
1882 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1884 # after we render the processing page, we quickly redirect to submit
1885 # the actual payment. The refresh url contains the payment token.
1886 # It also contains the list of xact IDs, which allows us to clear the
1887 # cache at the earliest possible time while leaving a trace of which
1888 # transactions we were processing, so the UI can bring the user back
1889 # to the payment form w/ the same xacts if the payment fails.
1891 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1892 $refresh .= ";xact=$_" for @payment_xacts;
1893 $self->ctx->{refresh} = $refresh;
1895 return Apache2::Const::OK;
1898 # retrieve the cached CC payment info and send off for processing
1899 sub load_myopac_pay {
1901 my $token = $self->ctx->{page_args}->[0];
1902 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1904 my $cache = OpenSRF::Utils::Cache->new('global');
1905 my $cache_args = $cache->get_cache($token);
1906 $cache->delete_cache($token);
1908 # this page is loaded immediately after the token is created.
1909 # if the cached data is not there, it's because of an invalid
1910 # token (or cache failure) and not because of a timeout.
1911 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1913 my @payment_xacts = @{$cache_args->{xacts}};
1914 my $cc_args = $cache_args->{cc_args};
1916 # as an added security check, verify the user submitting
1917 # the form is the same as the user whose data was cached
1918 return Apache2::Const::HTTP_BAD_REQUEST unless
1919 $cache_args->{user} == $self->ctx->{user}->id;
1921 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1924 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1926 # balance_owed is computed specifically from the fines we're paying
1927 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1928 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1929 return Apache2::Const::HTTP_BAD_REQUEST;
1933 "cc_args" => $cc_args,
1934 "userid" => $self->ctx->{user}->id,
1935 "payment_type" => "credit_card_payment",
1936 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1939 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1940 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1943 $self->ctx->{"payment_response"} = $resp;
1945 unless ($resp->{"textcode"}) {
1946 $self->ctx->{printable_receipt} = $U->simplereq(
1947 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1948 $self->editor->authtoken, $resp->{payments}
1952 return Apache2::Const::OK;
1955 sub load_myopac_receipt_print {
1958 $self->ctx->{printable_receipt} = $U->simplereq(
1959 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1960 $self->editor->authtoken, [$self->cgi->param("payment")]
1963 return Apache2::Const::OK;
1966 sub load_myopac_receipt_email {
1969 # The following ML method doesn't actually check whether the user in
1970 # question has an email address, so we do.
1971 if ($self->ctx->{user}->email) {
1972 $self->ctx->{email_receipt_result} = $U->simplereq(
1973 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1974 $self->editor->authtoken, [$self->cgi->param("payment")]
1977 $self->ctx->{email_receipt_result} =
1978 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1981 return Apache2::Const::OK;
1985 my ($self, $limit, $offset, $id_list) = @_;
1987 # XXX TODO: check for failure after various network calls
1989 # It may be unclear, but this result structure lumps circulation and
1990 # reservation fines together, and keeps grocery fines separate.
1991 $self->ctx->{"fines"} = {
1992 "circulation" => [],
1999 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2001 # TODO: This should really be a ML call, but the existing calls
2002 # return an excessive amount of data and don't offer streaming
2004 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2006 my $req = $cstore->request(
2007 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2009 usr => $self->editor->requestor->id,
2010 balance_owed => {'!=' => 0},
2011 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2016 mobts => [qw/grocery circulation reservation/],
2017 bresv => ['target_resource_type'],
2021 circ => ['target_copy'],
2022 acp => ['call_number'],
2025 order_by => { mobts => 'xact_start' },
2030 # Collect $$ amounts from each transaction for summing below.
2031 my (@paid_amounts, @owed_amounts, @balance_amounts);
2033 while(my $resp = $req->recv) {
2034 my $mobts = $resp->content;
2035 my $circ = $mobts->circulation;
2038 if($mobts->grocery) {
2039 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2040 $last_billing = pop(@billings);
2043 push(@paid_amounts, $mobts->total_paid);
2044 push(@owed_amounts, $mobts->total_owed);
2045 push(@balance_amounts, $mobts->balance_owed);
2047 my $marc_xml = undef;
2048 if ($mobts->xact_type eq 'reservation' and
2049 $mobts->reservation->target_resource_type->record) {
2050 $marc_xml = XML::LibXML->new->parse_string(
2051 $mobts->reservation->target_resource_type->record->marc
2053 } elsif ($mobts->xact_type eq 'circulation' and
2054 $circ->target_copy->call_number->id != -1) {
2055 $marc_xml = XML::LibXML->new->parse_string(
2056 $circ->target_copy->call_number->record->marc
2061 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2064 last_grocery_billing => $last_billing,
2065 marc_xml => $marc_xml
2072 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2073 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2074 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2079 sub prepare_fines_for_payment {
2080 # This assumes $self->prepare_fines has already been run
2084 if ($self->ctx->{fines}) {
2085 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2086 @{$self->ctx->{fines}->{circulation}},
2087 @{$self->ctx->{fines}->{grocery}}
2094 sub load_myopac_main {
2096 my $limit = $self->cgi->param('limit') || 0;
2097 my $offset = $self->cgi->param('offset') || 0;
2098 $self->ctx->{search_ou} = $self->_get_search_lib();
2099 $self->ctx->{user}->notes(
2100 $self->editor->search_actor_usr_note({
2101 usr => $self->ctx->{user}->id,
2105 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2108 sub load_myopac_update_email {
2110 my $e = $self->editor;
2111 my $ctx = $self->ctx;
2112 my $email = $self->cgi->param('email') || '';
2113 my $current_pw = $self->cgi->param('current_pw') || '';
2115 # needed for most up-to-date email address
2116 if (my $r = $self->prepare_extended_user_info) { return $r };
2118 return Apache2::Const::OK
2119 unless $self->cgi->request_method eq 'POST';
2121 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2122 $ctx->{invalid_email} = $email;
2123 return Apache2::Const::OK;
2126 my $stat = $U->simplereq(
2128 'open-ils.actor.user.email.update',
2129 $e->authtoken, $email, $current_pw);
2131 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2132 $ctx->{password_incorrect} = 1;
2133 return Apache2::Const::OK;
2136 unless ($self->cgi->param("redirect_to")) {
2137 my $url = $self->apache->unparsed_uri;
2138 $url =~ s/update_email/prefs/;
2140 return $self->generic_redirect($url);
2143 return $self->generic_redirect;
2146 sub load_myopac_update_username {
2148 my $e = $self->editor;
2149 my $ctx = $self->ctx;
2150 my $username = $self->cgi->param('username') || '';
2151 my $current_pw = $self->cgi->param('current_pw') || '';
2153 $self->prepare_extended_user_info;
2155 my $allow_change = 1;
2157 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2158 if(defined($lock_usernames) and $lock_usernames == 1) {
2159 # Policy says no username changes
2162 # We want this further down.
2163 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2164 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2165 if(!$username_unlimit) {
2167 # Default is "starts with a number"
2168 $regex_check = '^\d+';
2170 # You already have a username?
2171 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2176 if(!$allow_change) {
2177 my $url = $self->apache->unparsed_uri;
2178 $url =~ s/update_username/prefs/;
2180 return $self->generic_redirect($url);
2183 return Apache2::Const::OK
2184 unless $self->cgi->request_method eq 'POST';
2186 unless($username and $username !~ /\s/) { # any other username restrictions?
2187 $ctx->{invalid_username} = $username;
2188 return Apache2::Const::OK;
2191 # New username can't look like a barcode if we have a barcode regex
2192 if($regex_check and $username =~ /$regex_check/) {
2193 $ctx->{invalid_username} = $username;
2194 return Apache2::Const::OK;
2197 # New username has to look like a username if we have a username regex
2198 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2199 if($regex_check and $username !~ /$regex_check/) {
2200 $ctx->{invalid_username} = $username;
2201 return Apache2::Const::OK;
2204 if($username ne $e->requestor->usrname) {
2206 my $evt = $U->simplereq(
2208 'open-ils.actor.user.username.update',
2209 $e->authtoken, $username, $current_pw);
2211 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2212 $ctx->{password_incorrect} = 1;
2213 return Apache2::Const::OK;
2216 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2217 $ctx->{username_exists} = $username;
2218 return Apache2::Const::OK;
2222 my $url = $self->apache->unparsed_uri;
2223 $url =~ s/update_username/prefs/;
2225 return $self->generic_redirect($url);
2228 sub load_myopac_update_password {
2230 my $e = $self->editor;
2231 my $ctx = $self->ctx;
2233 return Apache2::Const::OK
2234 unless $self->cgi->request_method eq 'POST';
2236 my $current_pw = $self->cgi->param('current_pw') || '';
2237 my $new_pw = $self->cgi->param('new_pw') || '';
2238 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2240 unless($new_pw eq $new_pw2) {
2241 $ctx->{password_nomatch} = 1;
2242 return Apache2::Const::OK;
2245 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2248 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2249 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2252 if($pw_regex and $new_pw !~ /$pw_regex/) {
2253 $ctx->{password_invalid} = 1;
2254 return Apache2::Const::OK;
2257 my $evt = $U->simplereq(
2259 'open-ils.actor.user.password.update',
2260 $e->authtoken, $new_pw, $current_pw);
2263 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2264 $ctx->{password_incorrect} = 1;
2265 return Apache2::Const::OK;
2268 my $url = $self->apache->unparsed_uri;
2269 $url =~ s/update_password/prefs/;
2271 return $self->generic_redirect($url);
2274 sub _update_bookbag_metadata {
2275 my ($self, $bookbag) = @_;
2277 $bookbag->name($self->cgi->param("name"));
2278 $bookbag->description($self->cgi->param("description"));
2280 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2284 sub _get_lists_per_page {
2287 if($self->editor->requestor) {
2288 $self->timelog("Checking for opac.lists_per_page preference");
2289 # See if the user has a lists per page preference
2290 my $ipp = $self->editor->search_actor_user_setting({
2291 usr => $self->editor->requestor->id,
2292 name => 'opac.lists_per_page'
2294 $self->timelog("Got opac.lists_per_page preference");
2295 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2297 return 10; # default
2300 sub _get_items_per_page {
2303 if($self->editor->requestor) {
2304 $self->timelog("Checking for opac.list_items_per_page preference");
2305 # See if the user has a list items per page preference
2306 my $ipp = $self->editor->search_actor_user_setting({
2307 usr => $self->editor->requestor->id,
2308 name => 'opac.list_items_per_page'
2310 $self->timelog("Got opac.list_items_per_page preference");
2311 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2313 return 10; # default
2316 sub load_myopac_bookbags {
2318 my $e = $self->editor;
2319 my $ctx = $self->ctx;
2320 my $limit = $self->_get_lists_per_page || 10;
2321 my $offset = $self->cgi->param('offset') || 0;
2323 $ctx->{bookbags_limit} = $limit;
2324 $ctx->{bookbags_offset} = $offset;
2326 # for list item pagination
2327 my $item_limit = $self->_get_items_per_page;
2328 my $item_page = $self->cgi->param('item_page') || 1;
2329 my $item_offset = ($item_page - 1) * $item_limit;
2330 $ctx->{bookbags_item_page} = $item_page;
2332 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2333 $e->xact_begin; # replication...
2335 my $rv = $self->load_mylist;
2336 unless($rv eq Apache2::Const::OK) {
2341 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2343 {owner => $e->requestor->id, btype => 'bookbag'}, {
2344 order_by => {cbreb => 'name'},
2352 if(!$ctx->{bookbags}) {
2354 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2357 # We load the user prefs to get their default bookbag.
2358 $self->_load_user_with_prefs;
2360 # We also want a total count of the user's bookbags.
2362 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2364 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2366 my $r = $e->json_query($q);
2367 $ctx->{bookbag_count} = $r->[0]->{'count'};
2369 # If the user wants a specific bookbag's items, load them.
2371 if ($self->cgi->param("bbid")) {
2373 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2376 my $query = $self->_prepare_bookbag_container_query(
2377 $bookbag->id, $sorter, $modifier
2380 # Calculate total count of the items in selected bookbag.
2381 # This total includes record entries that have no assets available.
2382 my $bb_search_results = $U->simplereq(
2383 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2384 {"limit" => 1, "offset" => 0}, $query
2385 ); # we only need the count, so do the actual search with limit=1
2387 if ($bb_search_results) {
2388 $ctx->{bb_item_count} = $bb_search_results->{count};
2390 $logger->warn("search failed in load_myopac_bookbags()");
2391 $ctx->{bb_item_count} = 0; # fallback value
2394 #calculate page count
2395 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2397 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2398 if (!$self->_update_bookbag_metadata($bookbag)) {
2400 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2403 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2406 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2407 if ($self->cgi->param($param)) {
2408 my @vals = $self->cgi->param($param);
2409 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2413 return $self->generic_redirect($url);
2417 # we're done with our CStoreEditor. Rollback here so
2418 # later calls don't cause a timeout, resulting in a
2419 # transaction rollback under the covers.
2423 # For list items pagination
2425 "limit" => $item_limit,
2426 "offset" => $item_offset
2429 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2430 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2432 # capture pref_ou for callnumber filter/display
2433 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2435 # search for local callnumbers for display
2436 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2438 my (undef, @recs) = $self->get_records_and_facets(
2439 [ map {$_->target_biblio_record_entry->id} @$items ],
2442 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2444 site => $ctx->{get_aou}->($focus_ou)->shortname,
2445 pref_lib => $ctx->{pref_ou}
2449 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2451 $bookbag->items($items);
2455 # If we have add_rec, we got here from the "Add to new list"
2456 # or "See all" popmenu items.
2457 if (my $add_rec = $self->cgi->param('add_rec')) {
2458 $self->ctx->{add_rec} = $add_rec;
2459 # But not in the staff client, 'cause that breaks things.
2460 unless ($self->ctx->{is_staff}) {
2461 # allow caller to provide the where_from in cases where
2462 # the referer is an intermediate error page
2463 if ($self->cgi->param('where_from')) {
2464 $self->ctx->{where_from} = $self->cgi->param('where_from');
2466 $self->ctx->{where_from} = $self->ctx->{referer};
2467 if ( my $anchor = $self->cgi->param('anchor') ) {
2468 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2474 # this rollback may be a dupe, but that's OK because
2475 # cstoreditor ignores dupe rollbacks
2478 return Apache2::Const::OK;
2482 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
2483 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2484 sub load_myopac_bookbag_update {
2485 my ($self, $action, $list_id, @hold_recs) = @_;
2486 my $e = $self->editor;
2487 my $cgi = $self->cgi;
2489 # save_notes is effectively another action, but is passed in a separate
2490 # CGI parameter for what are really just layout reasons.
2491 $action = 'save_notes' if $cgi->param('save_notes');
2492 $action ||= $cgi->param('action');
2494 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2496 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2497 my @selected_item = $cgi->param('selected_item');
2498 my $shared = $cgi->param('shared');
2499 my $move_cart = $cgi->param('move_cart');
2500 my $name = $cgi->param('name');
2501 my $description = $cgi->param('description');
2505 # bail out if user is attempting an action that requires
2506 # that at least one list item be selected
2507 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
2508 ($action eq 'place_hold' || $action eq 'print' ||
2509 $action eq 'email' || $action eq 'del_item')) {
2510 my $url = $self->ctx->{referer};
2511 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
2512 return $self->generic_redirect($url);
2515 # This url intentionally leaves off the edit_notes parameter, but
2516 # may need to add some back in for paging.
2518 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2519 $self->ctx->{opac_root} . "/myopac/lists?";
2521 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2522 if ($cgi->param($param)) {
2523 my @vals = $cgi->param($param);
2524 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2528 if ($action eq 'create') {
2531 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2533 $list->description($description);
2534 $list->owner($e->requestor->id);
2535 $list->btype('bookbag');
2536 $list->pub($shared ? 't' : 'f');
2537 $success = $U->simplereq('open-ils.actor',
2538 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2539 if (ref($success) ne 'HASH') {
2540 $list_id = (ref($success)) ? $success->id : $success;
2541 if (scalar @add_rec) {
2542 foreach my $add_rec (@add_rec) {
2543 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2544 $item->bucket($list_id);
2545 $item->target_biblio_record_entry($add_rec);
2546 $success = $U->simplereq('open-ils.actor',
2547 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2548 last unless $success;
2552 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
2553 foreach my $add_rec (@$list) {
2554 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2555 $item->bucket($list_id);
2556 $item->target_biblio_record_entry($add_rec);
2557 $success = $U->simplereq('open-ils.actor',
2558 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2559 last unless $success;
2561 $self->clear_anon_cache;
2564 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
2567 $self->ctx->{bucket_failure_noname} = 1;
2570 } elsif($action eq 'place_hold') {
2572 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
2573 my $from_basket = scalar(@hold_recs);
2574 unless (@hold_recs) {
2575 if (@selected_item) {
2576 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
2577 @hold_recs = map { $_->target_biblio_record_entry } @$items;
2581 return Apache2::Const::OK unless @hold_recs;
2582 $logger->info("placing holds from list page on: @hold_recs");
2584 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
2585 $url .= ';hold_target=' . $_ for @hold_recs;
2586 $url .= ';from_basket=1' if $from_basket;
2587 foreach my $param (('loc', 'qtype', 'query')) {
2588 if ($cgi->param($param)) {
2589 my @vals = $cgi->param($param);
2590 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2593 return $self->generic_redirect($url);
2595 } elsif ($action eq 'print') {
2596 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@selected_item);
2597 return $self->load_mylist_print($temp_cache_key);
2598 } elsif ($action eq 'email') {
2599 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@selected_item);
2600 return $self->load_mylist_email($temp_cache_key);
2603 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
2605 return Apache2::Const::HTTP_BAD_REQUEST unless
2606 $list and $list->owner == $e->requestor->id;
2609 if($action eq 'delete') {
2610 $success = $U->simplereq('open-ils.actor',
2611 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
2613 # We check to see if we're deleting the user's default list.
2614 $self->_load_user_with_prefs;
2615 my $settings_map = $self->ctx->{user_setting_map};
2616 if ($$settings_map{'opac.default_list'} == $list_id) {
2617 # We unset the user's opac.default_list setting.
2618 $success = $U->simplereq(
2620 'open-ils.actor.patron.settings.update',
2623 { 'opac.default_list' => 0 }
2627 } elsif($action eq 'show') {
2628 unless($U->is_true($list->pub)) {
2630 $success = $U->simplereq('open-ils.actor',
2631 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2634 } elsif($action eq 'hide') {
2635 if($U->is_true($list->pub)) {
2637 $success = $U->simplereq('open-ils.actor',
2638 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2641 } elsif($action eq 'rename') {
2644 $success = $U->simplereq('open-ils.actor',
2645 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2648 } elsif($action eq 'add_rec') {
2649 foreach my $add_rec (@add_rec) {
2650 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2651 $item->bucket($list_id);
2652 $item->target_biblio_record_entry($add_rec);
2653 $success = $U->simplereq('open-ils.actor',
2654 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2655 last unless $success;
2657 # Redirect back where we came from if we have an anchor parameter:
2658 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
2659 $url = $self->ctx->{referer};
2660 $url =~ s/#.*|$/#$anchor/;
2661 } elsif ($cgi->param('where_from')) {
2662 # Or, if we have a "where_from" parameter.
2663 $url = $cgi->param('where_from');
2665 } elsif ($action eq 'del_item') {
2666 foreach (@selected_item) {
2667 $success = $U->simplereq(
2669 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
2671 last unless $success;
2673 } elsif ($action eq 'save_notes') {
2674 $success = $self->update_bookbag_item_notes;
2675 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
2676 } elsif ($action eq 'make_default') {
2677 $success = $U->simplereq(
2679 'open-ils.actor.patron.settings.update',
2682 { 'opac.default_list' => $list_id }
2684 } elsif ($action eq 'remove_default') {
2685 $success = $U->simplereq(
2687 'open-ils.actor.patron.settings.update',
2690 { 'opac.default_list' => 0 }
2694 return $self->generic_redirect($url) if $success;
2696 $self->ctx->{where_from} = $cgi->param('where_from');
2697 $self->ctx->{bucket_action} = $action;
2698 $self->ctx->{bucket_action_failed} = 1;
2699 return Apache2::Const::OK;
2702 sub update_bookbag_item_notes {
2704 my $e = $self->editor;
2706 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2707 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2709 # We're going to leverage an API call that's already been written to check
2710 # permissions appropriately.
2712 my $a = create OpenSRF::AppSession("open-ils.actor");
2713 my $method = "open-ils.actor.container.item_note.cud";
2715 for my $note_key (@note_keys) {
2718 my $id = ($note_key =~ /(\d+)/)[0];
2721 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2722 my $event = $e->die_event;
2723 $self->apache->log->warn(
2724 "error retrieving cbrebin id $id, got event " .
2728 $self->ctx->{bucket_action_event} = $event;
2732 if (length($self->cgi->param($note_key))) {
2733 $note->ischanged(1);
2734 $note->note($self->cgi->param($note_key));
2736 $note->isdeleted(1);
2739 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2741 if (defined $U->event_code($r)) {
2742 $self->apache->log->warn(
2743 "attempt to modify cbrebin " . $note->id .
2744 " returned event " . $r->{textcode}
2748 $self->ctx->{bucket_action_event} = $r;
2753 for my $item_key (@item_keys) {
2754 my $id = int(($item_key =~ /(\d+)/)[0]);
2755 my $text = $self->cgi->param($item_key);
2758 next unless length $text;
2760 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2765 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2767 if (defined $U->event_code($r)) {
2768 $self->apache->log->warn(
2769 "attempt to create cbrebin for item " . $note->item .
2770 " returned event " . $r->{textcode}
2774 $self->ctx->{bucket_action_event} = $r;
2783 sub load_myopac_bookbag_print {
2786 my $id = int($self->cgi->param("list"));
2788 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2791 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2795 # Get the bookbag object itself, assuming we're allowed to.
2796 if ($self->editor->allowed("VIEW_CONTAINER")) {
2798 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2800 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2804 "owner" => $self->editor->requestor->id,
2808 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2810 $bbag = pop @$bookbags;
2813 # If we have a bookbag we're allowed to look at, issue the A/T event
2814 # to get CSV, passing as a user param that search query we built before.
2816 $self->ctx->{csv} = $U->fire_object_event(
2817 undef, "container.biblio_record_entry_bucket.csv",
2818 $bbag, $self->editor->requestor->home_ou,
2819 undef, {"item_search" => $item_search}
2823 # Create a reasonable filename and set the content disposition to
2824 # provoke browser download dialogs.
2825 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2827 return $self->set_file_download_headers("$filename.csv");
2830 sub load_myopac_circ_history_export {
2832 my $e = $self->editor;
2833 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2835 my $circs = $self->fetch_user_circ_history(1);
2837 $self->ctx->{csv}->{circs} = $circs;
2838 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
2842 sub load_password_reset {
2844 my $cgi = $self->cgi;
2845 my $ctx = $self->ctx;
2846 my $barcode = $cgi->param('barcode');
2847 my $username = $cgi->param('username');
2848 my $email = $cgi->param('email');
2849 my $pwd1 = $cgi->param('pwd1');
2850 my $pwd2 = $cgi->param('pwd2');
2851 my $uuid = $ctx->{page_args}->[0];
2855 $logger->info("patron password reset with uuid $uuid");
2857 if ($pwd1 and $pwd2) {
2859 if ($pwd1 eq $pwd2) {
2861 my $response = $U->simplereq(
2863 'open-ils.actor.patron.password_reset.commit',
2866 $logger->info("patron password reset response " . Dumper($response));
2868 if ($U->event_code($response)) { # non-success event
2870 my $code = $response->{textcode};
2872 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2873 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2876 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2877 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2882 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2885 } else { # passwords not equal
2887 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2890 } else { # 2 password values needed
2892 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2895 } elsif ($barcode or $username) {
2897 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2898 push(@params, $email) if $email;
2902 'open-ils.actor.patron.password_reset.request', @params);
2904 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2907 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2908 return Apache2::Const::OK;