1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Cache;
11 use Digest::MD5 qw(md5_hex);
13 $Data::Dumper::Indent = 0;
15 my $U = 'OpenILS::Application::AppUtils';
17 sub prepare_extended_user_info {
20 my $e = $self->editor;
22 # are we already in a transaction?
23 my $local_xact = !$e->{xact_id};
24 $e->xact_begin if $local_xact;
26 # keep the original user object so we can restore
27 # login-specific data (e.g. workstation)
28 my $usr = $self->ctx->{user};
30 $self->ctx->{user} = $self->editor->retrieve_actor_user([
31 $self->ctx->{user}->id,
35 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
41 $e->rollback if $local_xact;
43 $self->ctx->{user}->wsid($usr->wsid);
44 $self->ctx->{user}->ws_ou($usr->ws_ou);
46 # discard replaced (negative-id) addresses.
47 $self->ctx->{user}->addresses([
48 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
50 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
51 unless $self->ctx->{user};
56 # Given an event returned by a failed attempt to create a hold, do we have
57 # permission to override? XXX Should the permission check be scoped to a
58 # given org_unit context?
59 sub test_could_override {
60 my ($self, $event) = @_;
62 return 0 unless $event;
63 return 1 if $self->editor->allowed($event->{textcode} . ".override");
64 return 1 if $event->{"fail_part"} and
65 $self->editor->allowed($event->{"fail_part"} . ".override");
69 # Find out whether we care that local copies are available
70 sub local_avail_concern {
71 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
73 my $would_block = $self->ctx->{get_org_setting}->
74 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
76 $self->ctx->{get_org_setting}->
77 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
78 not $self->cgi->param("override")
79 ) unless $would_block;
81 if ($would_block or $would_alert) {
83 "hold_target" => $hold_target,
84 "hold_type" => $hold_type,
85 "org_unit" => $pickup_lib
87 my $local_avail = $U->simplereq(
89 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
92 "copy availability information for " . Dumper($args) .
93 " is " . Dumper($local_avail)
95 if (%$local_avail) { # if hash not empty
96 $self->ctx->{hold_copy_available} = $local_avail;
97 return ($would_block, $would_alert);
105 # user : au object, fleshed
106 sub load_myopac_prefs {
108 my $cgi = $self->cgi;
109 my $e = $self->editor;
110 my $pending_addr = $cgi->param('pending_addr');
111 my $replace_addr = $cgi->param('replace_addr');
112 my $delete_pending = $cgi->param('delete_pending');
114 $self->prepare_extended_user_info;
115 my $user = $self->ctx->{user};
117 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
118 if(defined($lock_usernames) and $lock_usernames == 1) {
119 # Policy says no username changes
120 $self->ctx->{username_change_disallowed} = 1;
122 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
123 if(!$username_unlimit) {
124 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
126 # Default is "starts with a number"
127 $regex_check = '^\d+';
129 # You already have a username?
130 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
131 $self->ctx->{username_change_disallowed} = 1;
136 return Apache2::Const::OK unless
137 $pending_addr or $replace_addr or $delete_pending;
139 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
142 if( $pending_addr ) { # update an existing pending address
144 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
145 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
146 $paddr->$_( $cgi->param($_) ) for @form_fields;
148 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
150 $paddr = Fieldmapper::actor::user_address->new;
152 $paddr->usr($user->id);
153 $paddr->pending('t');
154 $paddr->replaces($replace_addr);
155 $paddr->$_( $cgi->param($_) ) for @form_fields;
157 } elsif( $delete_pending ) {
158 $paddr = $e->retrieve_actor_user_address($delete_pending);
159 return Apache2::Const::HTTP_BAD_REQUEST unless
160 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
161 $paddr->isdeleted(1);
164 my $resp = $U->simplereq(
166 'open-ils.actor.user.address.pending.cud',
167 $e->authtoken, $paddr);
169 if( $U->event_code($resp) ) {
170 $logger->error("Error updating pending address: $resp");
171 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
174 # in light of these changes, re-fetch latest data
176 $self->prepare_extended_user_info;
179 return Apache2::Const::OK;
182 sub load_myopac_prefs_notify {
184 my $e = $self->editor;
187 my $stat = $self->_load_user_with_prefs;
188 return $stat if $stat;
190 my $user_prefs = $self->fetch_optin_prefs;
191 $user_prefs = $self->update_optin_prefs($user_prefs)
192 if $self->cgi->request_method eq 'POST';
194 $self->ctx->{opt_in_settings} = $user_prefs;
196 return Apache2::Const::OK
197 unless $self->cgi->request_method eq 'POST';
200 my $set_map = $self->ctx->{user_setting_map};
204 opac.default_sms_notify
206 my $val = $self->cgi->param($key);
207 $settings{$key}= $val unless $$set_map{$key} eq $val;
210 my $key = 'opac.default_sms_carrier';
211 my $val = $self->cgi->param('sms_carrier');
212 $settings{$key}= $val unless $$set_map{$key} eq $val;
214 $key = 'opac.hold_notify';
215 my @notify_methods = ();
216 if ($self->cgi->param($key . ".email") eq 'on') {
217 push @notify_methods, "email";
219 if ($self->cgi->param($key . ".phone") eq 'on') {
220 push @notify_methods, "phone";
222 if ($self->cgi->param($key . ".sms") eq 'on') {
223 push @notify_methods, "sms";
225 $val = join("|",@notify_methods);
226 $settings{$key}= $val unless $$set_map{$key} eq $val;
228 # Send the modified settings off to be saved
231 'open-ils.actor.patron.settings.update',
232 $self->editor->authtoken, undef, \%settings);
234 # re-fetch user prefs
235 $self->ctx->{updated_user_settings} = \%settings;
236 return $self->_load_user_with_prefs || Apache2::Const::OK;
239 sub fetch_optin_prefs {
241 my $e = $self->editor;
243 # fetch all of the opt-in settings the user has access to
244 # XXX: user's should in theory have options to opt-in to notices
245 # for remote locations, but that opens the door for a large
246 # set of generally un-used opt-ins.. needs discussion
247 my $opt_ins = $U->simplereq(
249 'open-ils.actor.event_def.opt_in.settings.atomic',
250 $e->authtoken, $e->requestor->home_ou);
252 # some opt-ins are staff-only
253 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
255 # fetch user setting values for each of the opt-in settings
256 my $user_set = $U->simplereq(
258 'open-ils.actor.patron.settings.retrieve',
261 [map {$_->name} @$opt_ins]
264 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
267 sub _load_lists_and_settings {
269 my $e = $self->editor;
270 my $stat = $self->_load_user_with_prefs;
273 my $setting_map = $self->ctx->{user_setting_map};
274 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
275 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
277 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
278 order_by => {cbreb => 'name'},
279 limit => $self->cgi->param('limit') || 10,
280 offset => $self->cgi->param('offset') || 0
284 # We also want a total count of the user's bookbags.
286 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
288 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
290 my $r = $e->json_query($q);
291 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
292 # Someone has requested that we use the default list's name
293 # rather than "Default List."
296 'select' => {'cbreb' => ['name']},
298 'where' => {'id' => $exclude}
300 $r = $e->json_query($q);
301 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
309 sub update_optin_prefs {
311 my $user_prefs = shift;
312 my $e = $self->editor;
313 my @settings = $self->cgi->param('setting');
316 # apply now-true settings
317 for my $applied (@settings) {
318 # see if setting is already applied to this user
319 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
320 $newsets{$applied} = OpenSRF::Utils::JSON->true;
323 # remove now-false settings
324 for my $pref (grep { $_->{value} } @$user_prefs) {
325 $newsets{$pref->{cust}->name} = undef
326 unless grep { $_ eq $pref->{cust}->name } @settings;
331 'open-ils.actor.patron.settings.update',
332 $e->authtoken, $e->requestor->id, \%newsets);
334 # update the local prefs to match reality
335 for my $pref (@$user_prefs) {
336 $pref->{value} = $newsets{$pref->{cust}->name}
337 if exists $newsets{$pref->{cust}->name};
343 sub _load_user_with_prefs {
345 my $stat = $self->prepare_extended_user_info('settings');
346 return $stat if $stat; # not-OK
348 $self->ctx->{user_setting_map} = {
349 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
350 @{$self->ctx->{user}->settings}
356 sub _get_bookbag_sort_params {
357 my ($self, $param_name) = @_;
359 # The interface that feeds this cgi parameter will provide a single
360 # argument for a QP sort filter, and potentially a modifier after a period.
361 # In practice this means the "sort" parameter will be something like
362 # "titlesort" or "authorsort.descending".
363 my $sorter = $self->cgi->param($param_name) || "";
366 $sorter =~ s/^(.*?)\.(.*)/$1/;
367 $modifier = $2 || undef;
370 return ($sorter, $modifier);
373 sub _prepare_bookbag_container_query {
374 my ($self, $container_id, $sorter, $modifier) = @_;
377 "container(bre,bookbag,%d,%s)%s%s",
378 $container_id, $self->editor->authtoken,
379 ($sorter ? " sort($sorter)" : ""),
380 ($modifier ? "#$modifier" : "")
384 sub _prepare_anonlist_sorting_query {
385 my ($self, $list, $sorter, $modifier) = @_;
388 "record_list(%s)%s%s",
390 ($sorter ? " sort($sorter)" : ""),
391 ($modifier ? "#$modifier" : "")
396 sub load_myopac_prefs_settings {
401 opac.default_search_location
402 opac.default_pickup_location
403 opac.temporary_list_no_warn
406 my $stat = $self->_load_user_with_prefs;
407 return $stat if $stat;
409 # if behind-desk holds are supported and the user
410 # setting which controls the value is opac-visible,
411 # add the setting to the list of settings to manage.
412 # note: this logic may need to be changed later to
413 # check whether behind-the-desk holds are supported
414 # anywhere the patron may select as a pickup lib.
415 my $e = $self->editor;
416 my $bdous = $self->ctx->{get_org_setting}->(
417 $e->requestor->home_ou,
418 'circ.holds.behind_desk_pickup_supported');
422 $e->retrieve_config_usr_setting_type(
423 'circ.holds_behind_desk');
425 if ($U->is_true($setting->opac_visible)) {
426 push(@user_prefs, 'circ.holds_behind_desk');
427 $self->ctx->{behind_desk_supported} = 1;
431 return Apache2::Const::OK
432 unless $self->cgi->request_method eq 'POST';
434 # some setting values from the form don't match the
435 # required value/format for the db, so they have to be
436 # individually translated.
439 my $set_map = $self->ctx->{user_setting_map};
441 foreach my $key (@user_prefs) {
442 my $val = $self->cgi->param($key);
443 $settings{$key}= $val unless $$set_map{$key} eq $val;
446 my $now = DateTime->now->strftime('%F');
447 foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
448 my $val = $self->cgi->param($key);
449 if($val and $val eq 'on') {
450 # Set the start time to 'now' unless a start time already exists for the user
451 $settings{$key} = $now unless $$set_map{$key};
453 # clear the start time if one previously existed for the user
454 $settings{$key} = undef if $$set_map{$key};
458 # Send the modified settings off to be saved
461 'open-ils.actor.patron.settings.update',
462 $self->editor->authtoken, undef, \%settings);
464 # re-fetch user prefs
465 $self->ctx->{updated_user_settings} = \%settings;
466 return $self->_load_user_with_prefs || Apache2::Const::OK;
469 sub load_myopac_prefs_my_lists {
474 opac.list_items_per_page
477 my $stat = $self->_load_user_with_prefs;
478 return $stat if $stat;
480 return Apache2::Const::OK
481 unless $self->cgi->request_method eq 'POST';
484 my $set_map = $self->ctx->{user_setting_map};
486 foreach my $key (@user_prefs) {
487 my $val = $self->cgi->param($key);
488 $settings{$key}= $val unless $$set_map{$key} eq $val;
491 if (keys %settings) { # we found a different setting value
492 # Send the modified settings off to be saved
495 'open-ils.actor.patron.settings.update',
496 $self->editor->authtoken, undef, \%settings);
498 # re-fetch user prefs
499 $self->ctx->{updated_user_settings} = \%settings;
500 $stat = $self->_load_user_with_prefs;
503 return $stat || Apache2::Const::OK;
506 sub fetch_user_holds {
508 my $hold_ids = shift;
509 my $ids_only = shift;
511 my $available = shift;
515 my $e = $self->editor;
516 my $all_ids; # to be used below.
519 my $circ = OpenSRF::AppSession->create('open-ils.circ');
521 $hold_ids = $circ->request(
522 'open-ils.circ.holds.id_list.retrieve.authoritative',
529 $all_ids = $hold_ids;
530 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
533 $all_ids = $hold_ids;
536 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
539 suppress_notices => 1,
540 suppress_transits => 1,
542 suppress_patron_details => 1
545 # ----------------------------------------------------------------
546 # Collect holds in batches of $batch_size for faster retrieval
550 my $mk_req_batch = sub {
552 my $top_idx = $batch_idx + $batch_size;
553 while($batch_idx < $top_idx) {
554 my $hold_id = $hold_ids->[$batch_idx++];
555 last unless $hold_id;
556 my $ses = OpenSRF::AppSession->create('open-ils.circ');
557 my $req = $ses->request(
558 'open-ils.circ.hold.details.retrieve',
559 $e->authtoken, $hold_id, $args);
560 push(@ses, {ses => $ses, req => $req});
566 my(@collected, @holds, @ses);
569 @ses = $mk_req_batch->() if $first;
570 last if $first and not @ses;
573 while(my $blob = pop(@collected)) {
574 my (undef, @data) = $self->get_records_and_facets(
575 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
577 $blob->{marc_xml} = $data[0]->{marc_xml};
582 for my $req_data (@ses) {
583 push(@collected, {hold => $req_data->{req}->gather(1)});
584 $req_data->{ses}->kill_me;
587 @ses = $mk_req_batch->();
588 last unless @collected or @ses;
592 # put the holds back into the original server sort order
594 for my $id (@$hold_ids) {
595 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
598 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids };
601 sub handle_hold_update {
604 my $hold_ids = shift;
605 my $e = $self->editor;
608 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
609 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
611 my $circ = OpenSRF::AppSession->create('open-ils.circ');
613 if($action =~ /cancel/) {
615 for my $hold_id (@hold_ids) {
616 my $resp = $circ->request(
617 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
620 } elsif ($action =~ /activate|suspend/) {
623 for my $hold_id (@hold_ids) {
624 my $vals = {id => $hold_id};
626 if($action =~ /activate/) {
627 $vals->{frozen} = 'f';
628 $vals->{thaw_date} = undef;
630 } elsif($action =~ /suspend/) {
631 $vals->{frozen} = 't';
632 # $vals->{thaw_date} = TODO;
634 push(@$vlist, $vals);
637 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
638 $self->ctx->{hold_suspend_post_capture} = 1 if
639 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
641 } elsif ($action eq 'edit') {
644 my $val = {"id" => $_};
645 $val->{"frozen"} = $self->cgi->param("frozen");
646 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
648 for my $field (qw/expire_time thaw_date/) {
649 # XXX TODO make this support other date formats, not just
651 next unless $self->cgi->param($field) =~
652 m:^(\d{2})/(\d{2})/(\d{4})$:;
653 $val->{$field} = "$3-$1-$2";
659 'open-ils.circ.hold.update.batch.atomic',
660 $e->authtoken, undef, \@vals
661 )->gather(1); # LFW XXX test for failure
662 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
663 foreach my $param (('loc', 'qtype', 'query')) {
664 if ($self->cgi->param($param)) {
665 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
671 return defined($url) ? $self->generic_redirect($url) : undef;
674 sub load_myopac_holds {
676 my $e = $self->editor;
677 my $ctx = $self->ctx;
679 my $limit = $self->cgi->param('limit') || 15;
680 my $offset = $self->cgi->param('offset') || 0;
681 my $action = $self->cgi->param('action') || '';
682 my $hold_id = $self->cgi->param('id');
683 my $available = int($self->cgi->param('available') || 0);
685 my $hold_handle_result;
686 $hold_handle_result = $self->handle_hold_update($action) if $action;
688 my $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
689 if($holds_object->{holds}) {
690 $ctx->{holds} = $holds_object->{holds};
692 $ctx->{holds_ids} = $holds_object->{all_ids};
693 $ctx->{holds_limit} = $limit;
694 $ctx->{holds_offset} = $offset;
696 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
701 sub load_place_hold {
703 my $ctx = $self->ctx;
704 my $gos = $ctx->{get_org_setting};
705 my $e = $self->editor;
706 my $cgi = $self->cgi;
708 $self->ctx->{page} = 'place_hold';
709 my @targets = $cgi->param('hold_target');
710 my @parts = $cgi->param('part');
712 $ctx->{hold_type} = $cgi->param('hold_type');
713 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
714 $ctx->{email_notify} = $cgi->param('email_notify');
715 if ($cgi->param('phone_notify_checkbox')) {
716 $ctx->{phone_notify} = $cgi->param('phone_notify');
718 if ($cgi->param('sms_notify_checkbox')) {
719 $ctx->{sms_notify} = $cgi->param('sms_notify');
720 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
723 return $self->generic_redirect unless @targets;
725 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
727 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
732 au => ['settings', 'card']
735 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
736 my $user_setting_map = {
737 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
739 $ctx->{staff_recipient}->settings
742 $ctx->{user_setting_map} = $user_setting_map;
744 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
745 if ($default_notify =~ /email/) {
746 $ctx->{default_email_notify} = 'checked';
748 $ctx->{default_email_notify} = '';
750 if ($default_notify =~ /phone/) {
751 $ctx->{default_phone_notify} = 'checked';
753 $ctx->{default_phone_notify} = '';
755 if ($default_notify =~ /sms/) {
756 $ctx->{default_sms_notify} = 'checked';
758 $ctx->{default_sms_notify} = '';
761 # If we have a default pickup location, grab it
762 if ($$user_setting_map{'opac.default_pickup_location'}) {
763 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
766 my $request_lib = $e->requestor->ws_ou;
768 $ctx->{hold_data} = \@hold_data;
772 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
773 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
774 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
775 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
779 my $type_dispatch = {
781 my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
783 for my $id (@targets) { # force back into the correct order
784 my ($rec) = grep {$_->id eq $id} @$recs;
786 # NOTE: if tpac ever supports locked-down pickup libs,
787 # we'll need to pass a pickup_lib param along with the
788 # record to filter the set of monographic parts.
789 my $parts = $U->simplereq(
791 'open-ils.search.biblio.record_hold_parts',
795 # T holds on records that have parts are OK, but if the record has
796 # no non-part copies, the hold will ultimately fail. When that
797 # happens, require the user to select a part.
798 my $part_required = 0;
800 my $np_copies = $e->json_query({
801 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
802 from => {acp => {acn => {}, acpm => {type => 'left'}}},
804 '+acp' => {deleted => 'f'},
805 '+acn' => {deleted => 'f', record => $rec->id},
806 '+acpm' => {id => undef}
809 $part_required = 1 if $np_copies->[0]->{count} == 0;
812 push(@hold_data, $data_filler->({
816 part_required => $part_required
821 my $vols = $e->batch_retrieve_asset_call_number([
824 "flesh_fields" => {"acn" => ["record"]}
826 ], {substream => 1});
828 for my $id (@targets) {
829 my ($vol) = grep {$_->id eq $id} @$vols;
830 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
834 my $copies = $e->batch_retrieve_asset_copy([
839 "acp" => ["call_number"]
842 ], {substream => 1});
844 for my $id (@targets) {
845 my ($copy) = grep {$_->id eq $id} @$copies;
846 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
850 my $isses = $e->batch_retrieve_serial_issuance([
854 "siss" => ["subscription"], "ssub" => ["record_entry"]
857 ], {substream => 1});
859 for my $id (@targets) {
860 my ($iss) = grep {$_->id eq $id} @$isses;
861 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
866 }->{$ctx->{hold_type}}->();
868 # caller sent bad target IDs or the wrong hold type
869 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
871 # generate the MARC xml for each record
872 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
874 my $pickup_lib = $cgi->param('pickup_lib');
875 # no pickup lib means no holds placement
876 return Apache2::Const::OK unless $pickup_lib;
878 $ctx->{hold_attempt_made} = 1;
880 # Give the original CGI params back to the user in case they
881 # want to try to override something.
882 $ctx->{orig_params} = $cgi->Vars;
883 delete $ctx->{orig_params}{submit};
884 delete $ctx->{orig_params}{hold_target};
885 delete $ctx->{orig_params}{part};
887 my $usr = $e->requestor->id;
889 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
890 # find the real hold target
892 $usr = $U->simplereq(
894 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
895 $e->authtoken, $cgi->param("hold_usr"));
897 if (defined $U->event_code($usr)) {
898 $ctx->{hold_failed} = 1;
899 $ctx->{hold_failed_event} = $usr;
903 # target_id is the true target_id for holds placement.
904 # needed for attempt_hold_placement()
905 # With the exception of P-type holds, target_id == target->id.
906 $_->{target_id} = $_->{target}->id for @hold_data;
908 if ($ctx->{hold_type} eq 'T') {
910 # Much like quantum wave-particles, P-type holds pop into
911 # and out of existence at the user's whim. For our purposes,
912 # we treat such holds as T(itle) holds with a selected_part
913 # designation. When the time comes to pass the hold information
914 # off for holds possibility testing and placement, make it look
915 # like a real P-type hold.
916 my (@p_holds, @t_holds);
918 for my $idx (0..$#parts) {
919 my $hdata = $hold_data[$idx];
920 if (my $part = $parts[$idx]) {
921 $hdata->{target_id} = $part;
922 $hdata->{selected_part} = $part;
923 push(@p_holds, $hdata);
925 push(@t_holds, $hdata);
929 $self->apache->log->warn("$#parts : @t_holds");
931 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
932 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
935 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
938 # NOTE: we are leaving the staff-placed patron barcode cookie
939 # in place. Otherwise, it's not possible to place more than
940 # one hold for the patron within a staff/patron session. This
941 # does leave the barcode to linger longer than is ideal, but
942 # normal staff work flow will cause the cookie to be replaced
943 # with each new patron anyway.
944 # TODO: See about getting the staff client to clear the cookie
946 # return to the place_hold page so the results of the hold
947 # placement attempt can be reported to the user
948 return Apache2::Const::OK;
951 sub attempt_hold_placement {
952 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
953 my $cgi = $self->cgi;
954 my $ctx = $self->ctx;
955 my $e = $self->editor;
957 # First see if we should warn/block for any holds that
958 # might have locally available items.
959 for my $hdata (@hold_data) {
960 my ($local_block, $local_alert) = $self->local_avail_concern(
961 $hdata->{target_id}, $hold_type, $pickup_lib);
964 $hdata->{hold_failed} = 1;
965 $hdata->{hold_local_block} = 1;
966 } elsif ($local_alert) {
967 $hdata->{hold_failed} = 1;
968 $hdata->{hold_local_alert} = 1;
972 my $method = 'open-ils.circ.holds.test_and_create.batch';
974 if ($cgi->param('override')) {
975 $method .= '.override';
977 } elsif (!$ctx->{is_staff}) {
979 $method .= '.override' if $self->ctx->{get_org_setting}->(
980 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
983 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
985 if(@create_targets) {
987 my $bses = OpenSRF::AppSession->create('open-ils.circ');
988 my $breq = $bses->request(
991 $data_filler->({ patronid => $usr,
992 pickup_lib => $pickup_lib,
993 hold_type => $hold_type
998 while (my $resp = $breq->recv) {
1000 $resp = $resp->content;
1001 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1003 if ($U->event_code($resp)) {
1004 $ctx->{general_hold_error} = $resp;
1008 my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
1009 my $result = $resp->{result};
1011 if ($U->event_code($result)) {
1012 # e.g. permission denied
1013 $hdata->{hold_failed} = 1;
1014 $hdata->{hold_failed_event} = $result;
1018 if(not ref $result and $result > 0) {
1019 # successul hold returns the hold ID
1021 $hdata->{hold_success} = $result;
1024 # hold-specific failure event
1025 $hdata->{hold_failed} = 1;
1027 if (ref $result eq 'HASH') {
1028 $hdata->{hold_failed_event} = $result->{last_event};
1030 if ($result->{age_protected_copy}) {
1031 $hdata->{could_override} = 1;
1032 $hdata->{age_protect} = 1;
1034 $hdata->{could_override} = $result->{place_unfillable} ||
1035 $self->test_could_override($hdata->{hold_failed_event});
1037 } elsif (ref $result eq 'ARRAY') {
1038 $hdata->{hold_failed_event} = $result->[0];
1040 if ($result->[3]) { # age_protect_only
1041 $hdata->{could_override} = 1;
1042 $hdata->{age_protect} = 1;
1044 $hdata->{could_override} = $result->[4] || # place_unfillable
1045 $self->test_could_override($hdata->{hold_failed_event});
1056 sub fetch_user_circs {
1058 my $flesh = shift; # flesh bib data, etc.
1059 my $circ_ids = shift;
1063 my $e = $self->editor;
1068 @circ_ids = @$circ_ids;
1073 select => {circ => ['id']},
1077 usr => $e->requestor->id,
1078 checkin_time => undef,
1080 {stop_fines => undef},
1081 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1085 order_by => {circ => ['due_date']}
1088 $query->{limit} = $limit if $limit;
1089 $query->{offset} = $offset if $offset;
1091 my $ids = $e->json_query($query);
1092 @circ_ids = map {$_->{id}} @$ids;
1095 return [] unless @circ_ids;
1100 circ => ['target_copy'],
1101 acp => ['call_number'],
1107 my $circs = $e->search_action_circulation(
1108 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1111 for my $circ (@$circs) {
1114 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1115 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1116 undef # pre-cat copy, use the dummy title/author instead
1121 # make sure the final list is in the correct order
1123 for my $id (@circ_ids) {
1126 (grep { $_->{circ}->id == $id } @circs)
1130 return \@sorted_circs;
1134 sub handle_circ_renew {
1137 my $ctx = $self->ctx;
1139 my @renew_ids = $self->cgi->param('circ');
1141 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1143 # TODO: fire off renewal calls in batches to speed things up
1145 for my $circ (@$circs) {
1147 my $evt = $U->simplereq(
1149 'open-ils.circ.renew',
1150 $self->editor->authtoken,
1152 patron_id => $self->editor->requestor->id,
1153 copy_id => $circ->{circ}->target_copy,
1158 # TODO return these, then insert them into the circ data
1159 # blob that is shoved into the template for each circ
1160 # so the template won't have to match them
1161 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1168 sub load_myopac_circs {
1170 my $e = $self->editor;
1171 my $ctx = $self->ctx;
1174 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1175 my $offset = $self->cgi->param('offset') || 0;
1176 my $action = $self->cgi->param('action') || '';
1178 # perform the renewal first if necessary
1179 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1181 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1183 my $success_renewals = 0;
1184 my $failed_renewals = 0;
1185 for my $data (@{$ctx->{circs}}) {
1186 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1189 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1190 $data->{renewal_response} = $evt;
1191 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1192 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1196 $ctx->{success_renewals} = $success_renewals;
1197 $ctx->{failed_renewals} = $failed_renewals;
1199 return Apache2::Const::OK;
1202 sub load_myopac_circ_history {
1204 my $e = $self->editor;
1205 my $ctx = $self->ctx;
1206 my $limit = $self->cgi->param('limit') || 15;
1207 my $offset = $self->cgi->param('offset') || 0;
1209 $ctx->{circ_history_limit} = $limit;
1210 $ctx->{circ_history_offset} = $offset;
1212 my $circ_ids = $e->json_query({
1216 transform => 'action.usr_visible_circs',
1217 result_field => 'id'
1221 where => {id => $e->requestor->id},
1226 $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1227 return Apache2::Const::OK;
1230 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1231 sub load_myopac_hold_history {
1233 my $e = $self->editor;
1234 my $ctx = $self->ctx;
1235 my $limit = $self->cgi->param('limit') || 15;
1236 my $offset = $self->cgi->param('offset') || 0;
1237 $ctx->{hold_history_limit} = $limit;
1238 $ctx->{hold_history_offset} = $offset;
1240 my $hold_ids = $e->json_query({
1244 transform => 'action.usr_visible_holds',
1245 result_field => 'id'
1249 where => {id => $e->requestor->id}
1252 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1253 if($holds_object->{holds}) {
1254 $ctx->{holds} = $holds_object->{holds};
1256 $ctx->{hold_history_ids} = $holds_object->{all_ids};
1258 return Apache2::Const::OK;
1261 sub load_myopac_payment_form {
1265 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1266 $r = $self->prepare_extended_user_info and return $r;
1268 return Apache2::Const::OK;
1271 # TODO: add other filter options as params/configs/etc.
1272 sub load_myopac_payments {
1274 my $limit = $self->cgi->param('limit') || 20;
1275 my $offset = $self->cgi->param('offset') || 0;
1276 my $e = $self->editor;
1278 $self->ctx->{payment_history_limit} = $limit;
1279 $self->ctx->{payment_history_offset} = $offset;
1282 $args->{limit} = $limit if $limit;
1283 $args->{offset} = $offset if $offset;
1285 if (my $max_age = $self->ctx->{get_org_setting}->(
1286 $e->requestor->home_ou, "opac.payment_history_age_limit"
1288 my $min_ts = DateTime->now(
1289 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1290 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1292 $logger->info("XXX min_ts: $min_ts");
1293 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1296 $self->ctx->{payments} = $U->simplereq(
1298 'open-ils.actor.user.payments.retrieve.atomic',
1299 $e->authtoken, $e->requestor->id, $args);
1301 return Apache2::Const::OK;
1304 # 1. caches the form parameters
1305 # 2. loads the credit card payment "Processing..." page
1306 sub load_myopac_pay_init {
1308 my $cache = OpenSRF::Utils::Cache->new('global');
1310 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1312 if (!@payment_xacts) {
1313 # for consistency with load_myopac_payment_form() and
1314 # to preserve backwards compatibility, if no xacts are
1315 # selected, assume all (applicable) transactions are wanted.
1316 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1317 return $stat if $stat;
1319 map { $_->{xact}->id } (
1320 @{$self->ctx->{fines}->{circulation}},
1321 @{$self->ctx->{fines}->{grocery}}
1325 return $self->generic_redirect unless @payment_xacts;
1327 my $cc_args = {"where_process" => 1};
1329 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1330 number cvv2 expire_year expire_month billing_first
1331 billing_last billing_address billing_city billing_state
1336 cc_args => $cc_args,
1337 user => $self->ctx->{user}->id,
1338 xacts => \@payment_xacts
1341 # generate a temporary cache token and cache the form data
1342 my $token = md5_hex($$ . time() . rand());
1343 $cache->put_cache($token, $cache_args, 30);
1345 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1347 # after we render the processing page, we quickly redirect to submit
1348 # the actual payment. The refresh url contains the payment token.
1349 # It also contains the list of xact IDs, which allows us to clear the
1350 # cache at the earliest possible time while leaving a trace of which
1351 # transactions we were processing, so the UI can bring the user back
1352 # to the payment form w/ the same xacts if the payment fails.
1354 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1355 $refresh .= ";xact=$_" for @payment_xacts;
1356 $self->ctx->{refresh} = $refresh;
1358 return Apache2::Const::OK;
1361 # retrieve the cached CC payment info and send off for processing
1362 sub load_myopac_pay {
1364 my $token = $self->ctx->{page_args}->[0];
1365 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1367 my $cache = OpenSRF::Utils::Cache->new('global');
1368 my $cache_args = $cache->get_cache($token);
1369 $cache->delete_cache($token);
1371 # this page is loaded immediately after the token is created.
1372 # if the cached data is not there, it's because of an invalid
1373 # token (or cache failure) and not because of a timeout.
1374 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1376 my @payment_xacts = @{$cache_args->{xacts}};
1377 my $cc_args = $cache_args->{cc_args};
1379 # as an added security check, verify the user submitting
1380 # the form is the same as the user whose data was cached
1381 return Apache2::Const::HTTP_BAD_REQUEST unless
1382 $cache_args->{user} == $self->ctx->{user}->id;
1384 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1387 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1389 # balance_owed is computed specifically from the fines we're paying
1390 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1391 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1392 return Apache2::Const::HTTP_BAD_REQUEST;
1396 "cc_args" => $cc_args,
1397 "userid" => $self->ctx->{user}->id,
1398 "payment_type" => "credit_card_payment",
1399 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1402 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1403 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1406 $self->ctx->{"payment_response"} = $resp;
1408 unless ($resp->{"textcode"}) {
1409 $self->ctx->{printable_receipt} = $U->simplereq(
1410 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1411 $self->editor->authtoken, $resp->{payments}
1415 return Apache2::Const::OK;
1418 sub load_myopac_receipt_print {
1421 $self->ctx->{printable_receipt} = $U->simplereq(
1422 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1423 $self->editor->authtoken, [$self->cgi->param("payment")]
1426 return Apache2::Const::OK;
1429 sub load_myopac_receipt_email {
1432 # The following ML method doesn't actually check whether the user in
1433 # question has an email address, so we do.
1434 if ($self->ctx->{user}->email) {
1435 $self->ctx->{email_receipt_result} = $U->simplereq(
1436 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1437 $self->editor->authtoken, [$self->cgi->param("payment")]
1440 $self->ctx->{email_receipt_result} =
1441 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1444 return Apache2::Const::OK;
1448 my ($self, $limit, $offset, $id_list) = @_;
1450 # XXX TODO: check for failure after various network calls
1452 # It may be unclear, but this result structure lumps circulation and
1453 # reservation fines together, and keeps grocery fines separate.
1454 $self->ctx->{"fines"} = {
1455 "circulation" => [],
1462 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1464 # TODO: This should really be a ML call, but the existing calls
1465 # return an excessive amount of data and don't offer streaming
1467 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1469 my $req = $cstore->request(
1470 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1472 usr => $self->editor->requestor->id,
1473 balance_owed => {'!=' => 0},
1474 ($id_list && @$id_list ? ("id" => $id_list) : ()),
1479 mobts => [qw/grocery circulation reservation/],
1480 bresv => ['target_resource_type'],
1484 circ => ['target_copy'],
1485 acp => ['call_number'],
1488 order_by => { mobts => 'xact_start' },
1493 my @total_keys = qw/total_paid total_owed balance_owed/;
1494 $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1496 while(my $resp = $req->recv) {
1497 my $mobts = $resp->content;
1498 my $circ = $mobts->circulation;
1501 if($mobts->grocery) {
1502 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1503 $last_billing = pop(@billings);
1506 # XXX TODO confirm that the following, and the later division by 100.0
1507 # to get a floating point representation once again, is sufficiently
1508 # "money-safe" math.
1509 $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1511 my $marc_xml = undef;
1512 if ($mobts->xact_type eq 'reservation' and
1513 $mobts->reservation->target_resource_type->record) {
1514 $marc_xml = XML::LibXML->new->parse_string(
1515 $mobts->reservation->target_resource_type->record->marc
1517 } elsif ($mobts->xact_type eq 'circulation' and
1518 $circ->target_copy->call_number->id != -1) {
1519 $marc_xml = XML::LibXML->new->parse_string(
1520 $circ->target_copy->call_number->record->marc
1525 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1528 last_grocery_billing => $last_billing,
1529 marc_xml => $marc_xml
1536 $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1540 sub prepare_fines_for_payment {
1541 # This assumes $self->prepare_fines has already been run
1545 if ($self->ctx->{fines}) {
1546 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1547 @{$self->ctx->{fines}->{circulation}},
1548 @{$self->ctx->{fines}->{grocery}}
1555 sub load_myopac_main {
1557 my $limit = $self->cgi->param('limit') || 0;
1558 my $offset = $self->cgi->param('offset') || 0;
1559 $self->ctx->{search_ou} = $self->_get_search_lib();
1560 $self->ctx->{user}->notes(
1561 $self->editor->search_actor_usr_note({
1562 usr => $self->ctx->{user}->id,
1566 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1569 sub load_myopac_update_email {
1571 my $e = $self->editor;
1572 my $ctx = $self->ctx;
1573 my $email = $self->cgi->param('email') || '';
1574 my $current_pw = $self->cgi->param('current_pw') || '';
1576 # needed for most up-to-date email address
1577 if (my $r = $self->prepare_extended_user_info) { return $r };
1579 return Apache2::Const::OK
1580 unless $self->cgi->request_method eq 'POST';
1582 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1583 $ctx->{invalid_email} = $email;
1584 return Apache2::Const::OK;
1587 my $stat = $U->simplereq(
1589 'open-ils.actor.user.email.update',
1590 $e->authtoken, $email, $current_pw);
1592 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1593 $ctx->{password_incorrect} = 1;
1594 return Apache2::Const::OK;
1597 unless ($self->cgi->param("redirect_to")) {
1598 my $url = $self->apache->unparsed_uri;
1599 $url =~ s/update_email/prefs/;
1601 return $self->generic_redirect($url);
1604 return $self->generic_redirect;
1607 sub load_myopac_update_username {
1609 my $e = $self->editor;
1610 my $ctx = $self->ctx;
1611 my $username = $self->cgi->param('username') || '';
1612 my $current_pw = $self->cgi->param('current_pw') || '';
1614 $self->prepare_extended_user_info;
1616 my $allow_change = 1;
1618 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1619 if(defined($lock_usernames) and $lock_usernames == 1) {
1620 # Policy says no username changes
1623 # We want this further down.
1624 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1625 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1626 if(!$username_unlimit) {
1628 # Default is "starts with a number"
1629 $regex_check = '^\d+';
1631 # You already have a username?
1632 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1637 if(!$allow_change) {
1638 my $url = $self->apache->unparsed_uri;
1639 $url =~ s/update_username/prefs/;
1641 return $self->generic_redirect($url);
1644 return Apache2::Const::OK
1645 unless $self->cgi->request_method eq 'POST';
1647 unless($username and $username !~ /\s/) { # any other username restrictions?
1648 $ctx->{invalid_username} = $username;
1649 return Apache2::Const::OK;
1652 # New username can't look like a barcode if we have a barcode regex
1653 if($regex_check and $username =~ /$regex_check/) {
1654 $ctx->{invalid_username} = $username;
1655 return Apache2::Const::OK;
1658 # New username has to look like a username if we have a username regex
1659 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1660 if($regex_check and $username !~ /$regex_check/) {
1661 $ctx->{invalid_username} = $username;
1662 return Apache2::Const::OK;
1665 if($username ne $e->requestor->usrname) {
1667 my $evt = $U->simplereq(
1669 'open-ils.actor.user.username.update',
1670 $e->authtoken, $username, $current_pw);
1672 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1673 $ctx->{password_incorrect} = 1;
1674 return Apache2::Const::OK;
1677 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1678 $ctx->{username_exists} = $username;
1679 return Apache2::Const::OK;
1683 my $url = $self->apache->unparsed_uri;
1684 $url =~ s/update_username/prefs/;
1686 return $self->generic_redirect($url);
1689 sub load_myopac_update_password {
1691 my $e = $self->editor;
1692 my $ctx = $self->ctx;
1694 return Apache2::Const::OK
1695 unless $self->cgi->request_method eq 'POST';
1697 my $current_pw = $self->cgi->param('current_pw') || '';
1698 my $new_pw = $self->cgi->param('new_pw') || '';
1699 my $new_pw2 = $self->cgi->param('new_pw2') || '';
1701 unless($new_pw eq $new_pw2) {
1702 $ctx->{password_nomatch} = 1;
1703 return Apache2::Const::OK;
1706 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1709 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1710 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1713 if($pw_regex and $new_pw !~ /$pw_regex/) {
1714 $ctx->{password_invalid} = 1;
1715 return Apache2::Const::OK;
1718 my $evt = $U->simplereq(
1720 'open-ils.actor.user.password.update',
1721 $e->authtoken, $new_pw, $current_pw);
1724 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1725 $ctx->{password_incorrect} = 1;
1726 return Apache2::Const::OK;
1729 my $url = $self->apache->unparsed_uri;
1730 $url =~ s/update_password/prefs/;
1732 return $self->generic_redirect($url);
1735 sub _update_bookbag_metadata {
1736 my ($self, $bookbag) = @_;
1738 $bookbag->name($self->cgi->param("name"));
1739 $bookbag->description($self->cgi->param("description"));
1741 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1745 sub _get_lists_per_page {
1748 if($self->editor->requestor) {
1749 $self->timelog("Checking for opac.lists_per_page preference");
1750 # See if the user has a lists per page preference
1751 my $ipp = $self->editor->search_actor_user_setting({
1752 usr => $self->editor->requestor->id,
1753 name => 'opac.lists_per_page'
1755 $self->timelog("Got opac.lists_per_page preference");
1756 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
1758 return 10; # default
1761 sub _get_items_per_page {
1764 if($self->editor->requestor) {
1765 $self->timelog("Checking for opac.list_items_per_page preference");
1766 # See if the user has a list items per page preference
1767 my $ipp = $self->editor->search_actor_user_setting({
1768 usr => $self->editor->requestor->id,
1769 name => 'opac.list_items_per_page'
1771 $self->timelog("Got opac.list_items_per_page preference");
1772 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
1774 return 10; # default
1777 sub load_myopac_bookbags {
1779 my $e = $self->editor;
1780 my $ctx = $self->ctx;
1781 my $limit = $self->_get_lists_per_page || 10;
1782 my $offset = $self->cgi->param('offset') || 0;
1784 $ctx->{bookbags_limit} = $limit;
1785 $ctx->{bookbags_offset} = $offset;
1787 # for list item pagination
1788 my $item_limit = $self->_get_items_per_page;
1789 my $item_page = $self->cgi->param('item_page') || 1;
1790 my $item_offset = ($item_page - 1) * $item_limit;
1791 $ctx->{bookbags_item_page} = $item_page;
1793 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1794 $e->xact_begin; # replication...
1796 my $rv = $self->load_mylist;
1797 unless($rv eq Apache2::Const::OK) {
1802 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1804 {owner => $e->requestor->id, btype => 'bookbag'}, {
1805 order_by => {cbreb => 'name'},
1813 if(!$ctx->{bookbags}) {
1815 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1818 # We load the user prefs to get their default bookbag.
1819 $self->_load_user_with_prefs;
1821 # We also want a total count of the user's bookbags.
1823 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
1825 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
1827 my $r = $e->json_query($q);
1828 $ctx->{bookbag_count} = $r->[0]->{'count'};
1830 # If the user wants a specific bookbag's items, load them.
1832 if ($self->cgi->param("bbid")) {
1834 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
1837 my $query = $self->_prepare_bookbag_container_query(
1838 $bookbag->id, $sorter, $modifier
1841 # Calculate total count of the items in selected bookbag.
1842 # This total includes record entries that have no assets available.
1843 my $bb_search_results = $U->simplereq(
1844 "open-ils.search", "open-ils.search.biblio.multiclass.query",
1845 {"limit" => 1, "offset" => 0}, $query
1846 ); # we only need the count, so do the actual search with limit=1
1848 if ($bb_search_results) {
1849 $ctx->{bb_item_count} = $bb_search_results->{count};
1851 $logger->warn("search failed in load_myopac_bookbags()");
1852 $ctx->{bb_item_count} = 0; # fallback value
1855 #calculate page count
1856 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
1858 if ( ($self->cgi->param("action") || '') eq "editmeta") {
1859 if (!$self->_update_bookbag_metadata($bookbag)) {
1861 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1864 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
1867 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
1868 if ($self->cgi->param($param)) {
1869 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
1873 return $self->generic_redirect($url);
1877 # we're done with our CStoreEditor. Rollback here so
1878 # later calls don't cause a timeout, resulting in a
1879 # transaction rollback under the covers.
1883 # For list items pagination
1885 "limit" => $item_limit,
1886 "offset" => $item_offset
1889 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
1890 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1892 # capture pref_ou for callnumber filter/display
1893 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
1895 # search for local callnumbers for display
1896 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
1898 my (undef, @recs) = $self->get_records_and_facets(
1899 [ map {$_->target_biblio_record_entry->id} @$items ],
1902 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
1904 site => $ctx->{get_aou}->($focus_ou)->shortname,
1905 pref_lib => $ctx->{pref_ou}
1909 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1911 $bookbag->items($items);
1915 # If we have add_rec, we got here from the "Add to new list"
1916 # or "See all" popmenu items.
1917 if (my $add_rec = $self->cgi->param('add_rec')) {
1918 $self->ctx->{add_rec} = $add_rec;
1919 # But not in the staff client, 'cause that breaks things.
1920 unless ($self->ctx->{is_staff}) {
1921 # allow caller to provide the where_from in cases where
1922 # the referer is an intermediate error page
1923 if ($self->cgi->param('where_from')) {
1924 $self->ctx->{where_from} = $self->cgi->param('where_from');
1926 $self->ctx->{where_from} = $self->ctx->{referer};
1927 if ( my $anchor = $self->cgi->param('anchor') ) {
1928 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
1934 # this rollback may be a dupe, but that's OK because
1935 # cstoreditor ignores dupe rollbacks
1938 return Apache2::Const::OK;
1942 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1943 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1944 sub load_myopac_bookbag_update {
1945 my ($self, $action, $list_id, @hold_recs) = @_;
1946 my $e = $self->editor;
1947 my $cgi = $self->cgi;
1949 # save_notes is effectively another action, but is passed in a separate
1950 # CGI parameter for what are really just layout reasons.
1951 $action = 'save_notes' if $cgi->param('save_notes');
1952 $action ||= $cgi->param('action');
1954 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
1956 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1957 my @selected_item = $cgi->param('selected_item');
1958 my $shared = $cgi->param('shared');
1959 my $name = $cgi->param('name');
1960 my $description = $cgi->param('description');
1964 # This url intentionally leaves off the edit_notes parameter, but
1965 # may need to add some back in for paging.
1967 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
1968 $self->ctx->{opac_root} . "/myopac/lists?";
1970 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1971 if ($cgi->param($param)) {
1972 $url .= "$param=" . uri_escape_utf8($cgi->param($param)) . ";";
1976 if ($action eq 'create') {
1979 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1981 $list->description($description);
1982 $list->owner($e->requestor->id);
1983 $list->btype('bookbag');
1984 $list->pub($shared ? 't' : 'f');
1985 $success = $U->simplereq('open-ils.actor',
1986 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
1987 if (ref($success) ne 'HASH' && scalar @add_rec) {
1988 $list_id = (ref($success)) ? $success->id : $success;
1989 foreach my $add_rec (@add_rec) {
1990 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1991 $item->bucket($list_id);
1992 $item->target_biblio_record_entry($add_rec);
1993 $success = $U->simplereq('open-ils.actor',
1994 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1995 last unless $success;
1998 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
2001 $self->ctx->{bucket_failure_noname} = 1;
2004 } elsif($action eq 'place_hold') {
2006 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
2007 unless (@hold_recs) {
2008 if (@selected_item) {
2009 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
2010 @hold_recs = map { $_->target_biblio_record_entry } @$items;
2014 return Apache2::Const::OK unless @hold_recs;
2015 $logger->info("placing holds from list page on: @hold_recs");
2017 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
2018 $url .= ';hold_target=' . $_ for @hold_recs;
2019 foreach my $param (('loc', 'qtype', 'query')) {
2020 if ($cgi->param($param)) {
2021 $url .= ";$param=" . uri_escape_utf8($cgi->param($param));
2024 return $self->generic_redirect($url);
2028 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
2030 return Apache2::Const::HTTP_BAD_REQUEST unless
2031 $list and $list->owner == $e->requestor->id;
2034 if($action eq 'delete') {
2035 $success = $U->simplereq('open-ils.actor',
2036 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
2038 # We check to see if we're deleting the user's default list.
2039 $self->_load_user_with_prefs;
2040 my $settings_map = $self->ctx->{user_setting_map};
2041 if ($$settings_map{'opac.default_list'} == $list_id) {
2042 # We unset the user's opac.default_list setting.
2043 $success = $U->simplereq(
2045 'open-ils.actor.patron.settings.update',
2048 { 'opac.default_list' => 0 }
2052 } elsif($action eq 'show') {
2053 unless($U->is_true($list->pub)) {
2055 $success = $U->simplereq('open-ils.actor',
2056 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2059 } elsif($action eq 'hide') {
2060 if($U->is_true($list->pub)) {
2062 $success = $U->simplereq('open-ils.actor',
2063 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2066 } elsif($action eq 'rename') {
2069 $success = $U->simplereq('open-ils.actor',
2070 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2073 } elsif($action eq 'add_rec') {
2074 foreach my $add_rec (@add_rec) {
2075 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2076 $item->bucket($list_id);
2077 $item->target_biblio_record_entry($add_rec);
2078 $success = $U->simplereq('open-ils.actor',
2079 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2080 last unless $success;
2082 # Redirect back where we came from if we have an anchor parameter:
2083 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
2084 $url = $self->ctx->{referer};
2085 $url =~ s/#.*|$/#$anchor/;
2086 } elsif ($cgi->param('where_from')) {
2087 # Or, if we have a "where_from" parameter.
2088 $url = $cgi->param('where_from');
2090 } elsif ($action eq 'del_item') {
2091 foreach (@selected_item) {
2092 $success = $U->simplereq(
2094 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
2096 last unless $success;
2098 } elsif ($action eq 'save_notes') {
2099 $success = $self->update_bookbag_item_notes;
2100 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
2101 } elsif ($action eq 'make_default') {
2102 $success = $U->simplereq(
2104 'open-ils.actor.patron.settings.update',
2107 { 'opac.default_list' => $list_id }
2109 } elsif ($action eq 'remove_default') {
2110 $success = $U->simplereq(
2112 'open-ils.actor.patron.settings.update',
2115 { 'opac.default_list' => 0 }
2119 return $self->generic_redirect($url) if $success;
2121 $self->ctx->{where_from} = $cgi->param('where_from');
2122 $self->ctx->{bucket_action} = $action;
2123 $self->ctx->{bucket_action_failed} = 1;
2124 return Apache2::Const::OK;
2127 sub update_bookbag_item_notes {
2129 my $e = $self->editor;
2131 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2132 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2134 # We're going to leverage an API call that's already been written to check
2135 # permissions appropriately.
2137 my $a = create OpenSRF::AppSession("open-ils.actor");
2138 my $method = "open-ils.actor.container.item_note.cud";
2140 for my $note_key (@note_keys) {
2143 my $id = ($note_key =~ /(\d+)/)[0];
2146 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2147 my $event = $e->die_event;
2148 $self->apache->log->warn(
2149 "error retrieving cbrebin id $id, got event " .
2153 $self->ctx->{bucket_action_event} = $event;
2157 if (length($self->cgi->param($note_key))) {
2158 $note->ischanged(1);
2159 $note->note($self->cgi->param($note_key));
2161 $note->isdeleted(1);
2164 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2166 if (defined $U->event_code($r)) {
2167 $self->apache->log->warn(
2168 "attempt to modify cbrebin " . $note->id .
2169 " returned event " . $r->{textcode}
2173 $self->ctx->{bucket_action_event} = $r;
2178 for my $item_key (@item_keys) {
2179 my $id = int(($item_key =~ /(\d+)/)[0]);
2180 my $text = $self->cgi->param($item_key);
2183 next unless length $text;
2185 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2190 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2192 if (defined $U->event_code($r)) {
2193 $self->apache->log->warn(
2194 "attempt to create cbrebin for item " . $note->item .
2195 " returned event " . $r->{textcode}
2199 $self->ctx->{bucket_action_event} = $r;
2208 sub load_myopac_bookbag_print {
2211 my $id = int($self->cgi->param("list"));
2213 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2216 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2220 # Get the bookbag object itself, assuming we're allowed to.
2221 if ($self->editor->allowed("VIEW_CONTAINER")) {
2223 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2225 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2229 "owner" => $self->editor->requestor->id,
2233 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2235 $bbag = pop @$bookbags;
2238 # If we have a bookbag we're allowed to look at, issue the A/T event
2239 # to get CSV, passing as a user param that search query we built before.
2241 $self->ctx->{csv} = $U->fire_object_event(
2242 undef, "container.biblio_record_entry_bucket.csv",
2243 $bbag, $self->editor->requestor->home_ou,
2244 undef, {"item_search" => $item_search}
2248 # Create a reasonable filename and set the content disposition to
2249 # provoke browser download dialogs.
2250 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2252 return $self->set_file_download_headers("$filename.csv");
2255 sub load_myopac_circ_history_export {
2257 my $e = $self->editor;
2258 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2260 my $ids = $e->json_query({
2264 transform => 'action.usr_visible_circs',
2265 result_field => 'id'
2269 where => {id => $e->requestor->id}
2272 $self->ctx->{csv} = $U->fire_object_event(
2274 'circ.format.history.csv',
2275 $e->search_action_circulation({id => [map {$_->{id}} @$ids]}, {substream =>1}),
2276 $self->editor->requestor->home_ou
2279 return $self->set_file_download_headers($filename);
2282 sub load_password_reset {
2284 my $cgi = $self->cgi;
2285 my $ctx = $self->ctx;
2286 my $barcode = $cgi->param('barcode');
2287 my $username = $cgi->param('username');
2288 my $email = $cgi->param('email');
2289 my $pwd1 = $cgi->param('pwd1');
2290 my $pwd2 = $cgi->param('pwd2');
2291 my $uuid = $ctx->{page_args}->[0];
2295 $logger->info("patron password reset with uuid $uuid");
2297 if ($pwd1 and $pwd2) {
2299 if ($pwd1 eq $pwd2) {
2301 my $response = $U->simplereq(
2303 'open-ils.actor.patron.password_reset.commit',
2306 $logger->info("patron password reset response " . Dumper($response));
2308 if ($U->event_code($response)) { # non-success event
2310 my $code = $response->{textcode};
2312 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2313 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2316 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2317 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2322 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2325 } else { # passwords not equal
2327 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2330 } else { # 2 password values needed
2332 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2335 } elsif ($barcode or $username) {
2337 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2338 push(@params, $email) if $email;
2342 'open-ils.actor.patron.password_reset.request', @params);
2344 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2347 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2348 return Apache2::Const::OK;