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;
8 use OpenSRF::EX qw/:try/;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Cache;
12 use OpenILS::Utils::DateTime qw/:datetime/;
13 use Digest::MD5 qw(md5_hex);
16 $Data::Dumper::Indent = 0;
18 use DateTime::Format::ISO8601;
19 my $U = 'OpenILS::Application::AppUtils';
20 use List::MoreUtils qw/uniq/;
22 sub prepare_extended_user_info {
25 my $e = $self->editor;
27 # are we already in a transaction?
28 my $local_xact = !$e->{xact_id};
29 $e->xact_begin if $local_xact;
31 # keep the original user object so we can restore
32 # login-specific data (e.g. workstation)
33 my $usr = $self->ctx->{user};
35 $self->ctx->{user} = $self->editor->retrieve_actor_user([
36 $self->ctx->{user}->id,
40 au => [qw/card home_ou addresses ident_type billing_address waiver_entries/, @extra_flesh],
41 "aou" => ["billing_address"]
46 $e->rollback if $local_xact;
48 $self->ctx->{user}->wsid($usr->wsid);
49 $self->ctx->{user}->ws_ou($usr->ws_ou);
51 # discard replaced (negative-id) addresses.
52 $self->ctx->{user}->addresses([
53 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
55 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
56 unless $self->ctx->{user};
61 # Given an event returned by a failed attempt to create a hold, do we have
62 # permission to override? XXX Should the permission check be scoped to a
63 # given org_unit context?
64 sub test_could_override {
65 my ($self, $event) = @_;
67 return 0 unless $event;
68 return 1 if $self->editor->allowed($event->{textcode} . ".override");
69 return 1 if $event->{"fail_part"} and
70 $self->editor->allowed($event->{"fail_part"} . ".override");
74 # Find out whether we care that local copies are available
75 sub local_avail_concern {
76 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
78 my $would_block = $self->ctx->{get_org_setting}->
79 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
81 $self->ctx->{get_org_setting}->
82 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
83 not $self->cgi->param("override")
84 ) unless $would_block;
86 if ($would_block or $would_alert) {
88 "hold_target" => $hold_target,
89 "hold_type" => $hold_type,
90 "org_unit" => $pickup_lib
92 my $local_avail = $U->simplereq(
94 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
97 "copy availability information for " . Dumper($args) .
98 " is " . Dumper($local_avail)
100 if (%$local_avail) { # if hash not empty
101 $self->ctx->{hold_copy_available} = $local_avail;
102 return ($would_block, $would_alert);
110 # user : au object, fleshed
111 sub load_myopac_prefs {
113 my $cgi = $self->cgi;
114 my $e = $self->editor;
115 my $pending_addr = $cgi->param('pending_addr');
116 my $replace_addr = $cgi->param('replace_addr');
117 my $delete_pending = $cgi->param('delete_pending');
119 $self->prepare_extended_user_info;
120 my $user = $self->ctx->{user};
122 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
123 if(defined($lock_usernames) and $lock_usernames == 1) {
124 # Policy says no username changes
125 $self->ctx->{username_change_disallowed} = 1;
127 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
128 if(!$username_unlimit) {
129 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
131 # Default is "starts with a number"
132 $regex_check = '^\d+';
134 # You already have a username?
135 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
136 $self->ctx->{username_change_disallowed} = 1;
141 return Apache2::Const::OK unless
142 $pending_addr or $replace_addr or $delete_pending;
144 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
147 if( $pending_addr ) { # update an existing pending address
149 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
150 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
151 $paddr->$_( $cgi->param($_) ) for @form_fields;
153 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
155 $paddr = Fieldmapper::actor::user_address->new;
157 $paddr->usr($user->id);
158 $paddr->pending('t');
159 $paddr->replaces($replace_addr);
160 $paddr->$_( $cgi->param($_) ) for @form_fields;
162 } elsif( $delete_pending ) {
163 $paddr = $e->retrieve_actor_user_address($delete_pending);
164 return Apache2::Const::HTTP_BAD_REQUEST unless
165 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
166 $paddr->isdeleted(1);
169 my $resp = $U->simplereq(
171 'open-ils.actor.user.address.pending.cud',
172 $e->authtoken, $paddr);
174 if( $U->event_code($resp) ) {
175 $logger->error("Error updating pending address: $resp");
176 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
179 # in light of these changes, re-fetch latest data
181 $self->prepare_extended_user_info;
184 return Apache2::Const::OK;
187 sub load_myopac_prefs_notify {
189 my $e = $self->editor;
192 my $stat = $self->_load_user_with_prefs;
193 return $stat if $stat;
195 my $user_prefs = $self->fetch_optin_prefs;
196 $user_prefs = $self->update_optin_prefs($user_prefs)
197 if $self->cgi->request_method eq 'POST';
199 $self->ctx->{opt_in_settings} = $user_prefs;
201 return Apache2::Const::OK
202 unless $self->cgi->request_method eq 'POST';
205 my $set_map = $self->ctx->{user_setting_map};
209 opac.default_sms_notify
211 my $val = $self->cgi->param($key);
212 $settings{$key}= $val unless $$set_map{$key} eq $val;
215 my $key = 'opac.default_sms_carrier';
216 my $val = $self->cgi->param('sms_carrier');
217 $settings{$key}= $val unless $$set_map{$key} eq $val;
219 $key = 'opac.hold_notify';
220 my @notify_methods = ();
221 if ($self->cgi->param($key . ".email") eq 'on') {
222 push @notify_methods, "email";
224 if ($self->cgi->param($key . ".phone") eq 'on') {
225 push @notify_methods, "phone";
227 if ($self->cgi->param($key . ".sms") eq 'on') {
228 push @notify_methods, "sms";
230 $val = join("|",@notify_methods);
231 $settings{$key}= $val unless $$set_map{$key} eq $val;
233 # Send the modified settings off to be saved
236 'open-ils.actor.patron.settings.update',
237 $self->editor->authtoken, undef, \%settings);
239 # re-fetch user prefs
240 $self->ctx->{updated_user_settings} = \%settings;
242 # update holds: check if any changes affect any holds
243 my @llchgs = $self->_parse_prefs_notify_hold_related();
246 if ( $self->cgi->param('hasHoldsChanges') ) {
247 # propagate pref_notify changes to holds
248 for my $chset (@llchgs){
249 # FIXME is this still needed?
254 my $holds = $U->simplereq('open-ils.circ', 'open-ils.circ.holds.retrieve.by_usr.with_notify',
255 $e->authtoken, $e->requestor->id);
259 my $default_phone_changes = {};
260 my $sms_changes = {};
264 for my $chset (@llchgs) {
265 next if scalar(@$chset) < 3;
266 my ($old, $new, $field) = @$chset;
268 my $bool = $field =~ /_notify/ ? 1 : 0;
270 # find holds that would change
272 foreach my $hold (@$holds) {
273 if ($field eq 'email_notify') {
274 my $curr = $hold->{$field} eq 't' ? 'true' : 'false';
275 push @$affected, $hold if $curr ne $new;
276 } elsif ($field eq 'default_phone') {
277 my $old_phone = $hold->{phone_notify} // '';
278 $new_phone = $new // '';
279 push @{ $default_phone_changes->{ $old_phone } }, $hold->{id}
280 if $old_phone ne $new_phone;
281 } elsif ($field eq 'phone_notify') {
282 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
283 push @$affected, $hold if $curr ne $new;
284 } elsif ($field eq 'sms_notify') {
285 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
286 push @$affected, $hold if $curr ne $new;
287 } elsif ($field eq 'sms_info') {
288 my $old_carrier = $hold->{'sms_carrier'} // '';
289 my $old_sms = $hold->{'sms_notify'} // '';
290 $new_carrier = $new->{carrier} // '';
291 $new_sms = $new->{sms} // '';
292 if (!($old_carrier eq $new_carrier && $old_sms eq $new_sms)) {
293 push @{ $sms_changes->{ join("\t", $old_carrier, $old_sms) } }, $hold->{id};
298 # append affected array to chset
299 if (scalar(@$affected) > 0){
300 push(@$chset, [ map { $_->{id} } @$affected ]);
301 push(@ffectedChgs, $chset);
306 foreach my $old_phone (keys %$default_phone_changes) {
307 push(@ffectedChgs, [ $old_phone, $new_phone, 'default_phone', $default_phone_changes->{$old_phone} ]);
309 foreach my $old_sms_info (keys %$sms_changes) {
310 my ($old_carrier, $old_sms) = split /\t/, $old_sms_info;
312 { carrier => $old_carrier, sms => $old_sms },
313 { carrier => $new_carrier, sms => $new_sms },
315 $sms_changes->{$old_sms_info}
319 if ( scalar(@ffectedChgs) ){
320 $self->ctx->{affectedChgs} = \@ffectedChgs;
325 return $self->_load_user_with_prefs || Apache2::Const::OK;
328 sub _parse_prefs_notify_hold_related {
331 my $for_update = shift;
333 # create an array of change arrays
336 my @phone_notify = $self->cgi->multi_param('phone_notify[]');
337 push(@chgs, \@phone_notify) if scalar(@phone_notify);
339 my $turning_on_phone_notify = !$for_update &&
340 scalar(@phone_notify) &&
341 $phone_notify[1] eq 'true';
342 my $turning_off_phone_notify = !$for_update &&
343 scalar(@phone_notify) &&
344 $phone_notify[1] eq 'false';
346 my $changing_default_phone = 0;
347 if (!$turning_off_phone_notify) {
348 my @default_phone = $self->cgi->multi_param('default_phone[]');
350 while (scalar(@default_phone) > 0) {
351 my $chg = [ splice(@default_phone, 0, 4) ];
352 if (scalar(@default_phone) > 0 && $default_phone[0] eq 'on') {
353 push @$chg, shift(@default_phone);
355 $changing_default_phone = 1;
359 if (scalar(@default_phone)) {
360 push @chgs, \@default_phone;
361 $changing_default_phone = 1;
366 if ($turning_on_phone_notify && $changing_default_phone) {
367 # we don't need to have both the phone_notify and default_phone
368 # changes; the latter will suffice
369 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
370 } elsif ($turning_on_phone_notify && !$changing_default_phone) {
371 # replace the phone_notify change with a default_phone change
372 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
373 my $default_phone = $self->cgi->param('opac.default_phone'); # we assume this is set
374 push @chgs, [ '', $default_phone, 'default_phone' ];
378 # ... since both carrier and number are needed to send an SMS notifcation,
379 # we need to treat the pair as a unit
380 my @sms_notify = $self->cgi->multi_param('sms_notify[]');
381 push(@chgs, \@sms_notify) if scalar(@sms_notify);
383 my $turning_on_sms_notify = !$for_update &&
384 scalar(@sms_notify) &&
385 $sms_notify[1] eq 'true';
386 my $turning_off_sms_notify = !$for_update &&
387 scalar(@sms_notify) &&
388 $sms_notify[1] eq 'false';
390 my $changing_sms_info = 0;
391 if (!$turning_off_sms_notify) {
392 my @sms_carrier = $self->cgi->multi_param('default_sms_carrier_id[]');
393 my @sms = $self->cgi->multi_param('default_sms[]');
395 if (scalar(@sms) || scalar(@sms_carrier)) {
396 my $new_carrier = scalar(@sms_carrier) ? $sms_carrier[1] : $self->cgi->param('sms_carrier');
397 my $new_sms = scalar(@sms) ? $sms[1] : $self->cgi->param('opac.default_sms_notify');
399 { carrier => '', sms => '' },
400 { carrier => $new_carrier, sms => $new_sms },
403 $changing_sms_info = 1;
407 my @sms_info = $self->cgi->multi_param('sms_info[]'); # only sent by confirmation page
408 if (scalar(@sms_info)) {
409 while (scalar(@sms_info) > 0) {
410 my $chg = [ splice(@sms_info, 0, 4) ];
411 if (scalar(@sms_info) > 0 && $sms_info[0] eq 'on') {
412 push @$chg, shift(@sms_info);
413 my ($carrier, $sms) = split /,/, $chg->[0], -1;
414 $chg->[0] = { carrier => $carrier, sms => $sms };
415 ($carrier, $sms) = split /,/, $chg->[1], -1;
416 $chg->[1] = { carrier => $carrier, sms => $sms };
418 $changing_sms_info = 1;
423 if ($turning_on_sms_notify && $changing_sms_info) {
424 # we don't need to have both the sms_notify and sms_info
425 # changes; the latter will suffice
426 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
427 } elsif ($turning_on_sms_notify && !$changing_sms_info) {
428 # replace the sms_notify change with a sms_info change
429 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
431 carrier => $self->cgi->param('sms_carrier'),
432 sms => $self->cgi->param('opac.default_sms_notify'),
434 push @chgs, [ { carrier => '', sms => ''}, $sms_info, 'sms_info' ];
437 my @email_notify = $self->cgi->multi_param('email_notify[]');
438 push(@chgs, \@email_notify) if scalar(@email_notify);
441 # if we're updating, keep only the ones that have been
442 # explicitly checked by the user
443 @chgs = grep { scalar(@$_) == 5 && $_->[4] eq 'on' } @chgs;
448 sub load_myopac_prefs_notify_changed_holds {
450 my $e = $self->editor;
452 my $hasChanges = $self->cgi->param('hasHoldsChanges');
454 return $self->_load_user_with_prefs || Apache2::Const::OK unless $hasChanges;
456 my @ll = $self->_parse_prefs_notify_hold_related(1);
460 my ($old, $new, $type, $holdids, $doit) = @$chset;
461 next if $doit ne 'on';
463 # parse string list into array list
464 my @holdids = split(',', $holdids);
466 if ($type =~ /_notify/){
467 # translate true/false string into 1/0
468 $old = $old eq 'true' ? 1 : 0;
469 $new = $new eq 'true' ? 1 : 0;
473 if ($type eq 'sms_info') {
474 if ($new->{carrier} eq '' && $new->{sms} eq '') {
475 # clear SMS number first to avoid check contrainst issue
476 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
477 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
478 push (@updates, $update) if (scalar(@$update) > 0);
479 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
480 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
481 push (@updates, $update) if (scalar(@$update) > 0);
483 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
484 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
485 push (@updates, $update) if (scalar(@$update) > 0);
486 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
487 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
488 push (@updates, $update) if (scalar(@$update) > 0);
491 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
492 $e->authtoken, $e->requestor->id, [@holdids], $old, $new, $type);
494 # append affected array to chset
495 if (scalar(@$update) > 0){
496 push(@updates, $update);
501 $self->ctx->{'updated'} = \@updates;
503 return $self->_load_user_with_prefs || Apache2::Const::OK;
507 sub fetch_optin_prefs {
509 my $e = $self->editor;
511 # fetch all of the opt-in settings the user has access to
512 # XXX: user's should in theory have options to opt-in to notices
513 # for remote locations, but that opens the door for a large
514 # set of generally un-used opt-ins.. needs discussion
515 my $opt_ins = $U->simplereq(
517 'open-ils.actor.event_def.opt_in.settings.atomic',
518 $e->authtoken, $e->requestor->home_ou);
520 # some opt-ins are staff-only
521 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
523 # fetch user setting values for each of the opt-in settings
524 my $user_set = $U->simplereq(
526 'open-ils.actor.patron.settings.retrieve',
529 [map {$_->name} @$opt_ins]
532 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
535 sub load_myopac_messages {
537 my $e = $self->editor;
538 my $ctx = $self->ctx;
539 my $cgi = $self->cgi;
541 my $limit = $cgi->param('limit') || 20;
542 my $offset = $cgi->param('offset') || 0;
544 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
547 my $action = $cgi->param('action') || '';
549 my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
550 if ($changed > 0 || $failed > 0) {
551 $ctx->{message_update_action} = $action;
552 $ctx->{message_update_changed} = $changed;
553 $ctx->{message_update_failed} = $failed;
554 $self->update_dashboard_stats();
558 my $single = $cgi->param('single') || 0;
559 my $id = $cgi->param('message_id');
563 if (!$action && $single && $id) {
564 $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
565 if (scalar(@$messages) == 1) {
566 $ctx->{display_single_message} = 1;
567 $ctx->{patron_message_id} = $id;
573 # fetch all the messages
574 ($ctx->{patron_messages_count}, $messages) =
575 $self->_fetch_user_messages($pcrud, $offset, $limit);
580 foreach my $aum (@$messages) {
582 push @{ $ctx->{patron_messages} }, {
584 title => $aum->title,
585 message => $aum->message,
586 create_date => $aum->create_date,
587 edit_date => $aum->edit_date,
588 is_read => defined($aum->read_date) ? 1 : 0,
589 library => $aum->sending_lib->name,
593 $ctx->{patron_messages_limit} = $limit;
594 $ctx->{patron_messages_offset} = $offset;
596 return Apache2::Const::OK;
599 sub _fetch_and_mark_read_single_message {
604 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
605 my $messages = $pcrud->request(
606 'open-ils.pcrud.search.auml.atomic',
607 $self->editor->authtoken,
609 usr => $self->editor->requestor->id,
615 flesh_fields => { auml => ['sending_lib'] },
619 $messages->[0]->read_date('now');
621 'open-ils.pcrud.update.auml',
622 $self->editor->authtoken,
626 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
628 $self->update_dashboard_stats();
633 sub _fetch_user_messages {
639 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
641 my $all_messages = $pcrud->request(
642 'open-ils.pcrud.id_list.auml.atomic',
643 $self->editor->authtoken,
645 usr => $self->editor->requestor->id,
651 my $messages = $pcrud->request(
652 'open-ils.pcrud.search.auml.atomic',
653 $self->editor->authtoken,
655 usr => $self->editor->requestor->id,
660 flesh_fields => { auml => ['sending_lib'] },
661 order_by => { auml => 'create_date DESC' },
666 return scalar(@$all_messages), $messages;
669 sub _handle_message_action {
673 my $cgi = $self->cgi;
675 my @ids = $cgi->param('message_id');
676 return (0, 0) unless @ids;
680 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
682 my $aum = $pcrud->request(
683 'open-ils.pcrud.retrieve.auml',
684 $self->editor->authtoken,
688 if ($action eq 'mark_read') {
689 $aum->read_date('now');
690 } elsif ($action eq 'mark_unread') {
691 $aum->clear_read_date();
692 } elsif ($action eq 'mark_deleted') {
695 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
700 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
702 $failed = scalar(@ids);
704 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
706 return ($changed, $failed);
709 sub _load_lists_and_settings {
711 my $e = $self->editor;
712 my $stat = $self->_load_user_with_prefs;
715 my $setting_map = $self->ctx->{user_setting_map};
716 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
717 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
719 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
720 order_by => {cbreb => 'name'},
721 limit => $self->cgi->param('limit') || 10,
722 offset => $self->cgi->param('offset') || 0
726 # We also want a total count of the user's bookbags.
728 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
730 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
732 my $r = $e->json_query($q);
733 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
734 # Someone has requested that we use the default list's name
735 # rather than "Default List."
738 'select' => {'cbreb' => ['name']},
740 'where' => {'id' => $exclude}
742 $r = $e->json_query($q);
743 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
751 sub update_optin_prefs {
753 my $user_prefs = shift;
754 my $e = $self->editor;
755 my @settings = $self->cgi->param('setting');
758 # apply now-true settings
759 for my $applied (@settings) {
760 # see if setting is already applied to this user
761 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
762 $newsets{$applied} = OpenSRF::Utils::JSON->true;
765 # remove now-false settings
766 for my $pref (grep { $_->{value} } @$user_prefs) {
767 $newsets{$pref->{cust}->name} = undef
768 unless grep { $_ eq $pref->{cust}->name } @settings;
773 'open-ils.actor.patron.settings.update',
774 $e->authtoken, $e->requestor->id, \%newsets);
776 # update the local prefs to match reality
777 for my $pref (@$user_prefs) {
778 $pref->{value} = $newsets{$pref->{cust}->name}
779 if exists $newsets{$pref->{cust}->name};
785 sub _load_user_with_prefs {
787 my $stat = $self->prepare_extended_user_info('settings');
788 return $stat if $stat; # not-OK
790 $self->ctx->{user_setting_map} = {
791 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
792 @{$self->ctx->{user}->settings}
798 sub _get_bookbag_sort_params {
799 my ($self, $param_name) = @_;
801 # The interface that feeds this cgi parameter will provide a single
802 # argument for a QP sort filter, and potentially a modifier after a period.
803 # In practice this means the "sort" parameter will be something like
804 # "titlesort" or "authorsort.descending".
805 my $sorter = $self->cgi->param($param_name) || "";
808 $sorter =~ s/^(.*?)\.(.*)/$1/;
809 $modifier = $2 || undef;
812 return ($sorter, $modifier);
815 sub _prepare_bookbag_container_query {
816 my ($self, $container_id, $sorter, $modifier) = @_;
819 "container(bre,bookbag,%d,%s)%s%s",
820 $container_id, $self->editor->authtoken,
821 ($sorter ? " sort($sorter)" : ""),
822 ($modifier ? "#$modifier" : "")
826 sub _prepare_anonlist_sorting_query {
827 my ($self, $list, $sorter, $modifier) = @_;
830 "record_list(%s)%s%s",
832 ($sorter ? " sort($sorter)" : ""),
833 ($modifier ? "#$modifier" : "")
838 sub load_myopac_prefs_settings {
843 opac.default_search_location
844 opac.default_pickup_location
845 opac.temporary_list_no_warn
848 my $stat = $self->_load_user_with_prefs;
849 return $stat if $stat;
851 # if behind-desk holds are supported and the user
852 # setting which controls the value is opac-visible,
853 # add the setting to the list of settings to manage.
854 # note: this logic may need to be changed later to
855 # check whether behind-the-desk holds are supported
856 # anywhere the patron may select as a pickup lib.
857 my $e = $self->editor;
858 my $bdous = $self->ctx->{get_org_setting}->(
859 $e->requestor->home_ou,
860 'circ.holds.behind_desk_pickup_supported');
864 $e->retrieve_config_usr_setting_type(
865 'circ.holds_behind_desk');
867 if ($U->is_true($setting->opac_visible)) {
868 push(@user_prefs, 'circ.holds_behind_desk');
869 $self->ctx->{behind_desk_supported} = 1;
873 my $use_privacy_waiver = $self->ctx->{get_org_setting}->(
874 $e->requestor->home_ou, 'circ.privacy_waiver');
876 return Apache2::Const::OK
877 unless $self->cgi->request_method eq 'POST';
879 # some setting values from the form don't match the
880 # required value/format for the db, so they have to be
881 # individually translated.
884 my $set_map = $self->ctx->{user_setting_map};
886 foreach my $key (@user_prefs) {
887 my $val = $self->cgi->param($key);
888 $settings{$key}= $val unless $$set_map{$key} eq $val;
891 # Used by the settings update form when warning on history delete.
892 my $clear_circ_history = 0;
893 my $clear_hold_history = 0;
895 # true if we need to show the warning on next page load.
896 my $hist_warning_needed = 0;
897 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
899 my $now = DateTime->now->strftime('%F');
901 qw/history.circ.retention_start history.hold.retention_start/) {
903 my $val = $self->cgi->param($key);
904 if($val and $val eq 'on') {
905 # Set the start time to 'now' unless a start time already exists for the user
906 $settings{$key} = $now unless $$set_map{$key};
910 next unless $$set_map{$key}; # nothing to do
912 $clear_circ_history = 1 if $key =~ /circ/;
913 $clear_hold_history = 1 if $key =~ /hold/;
915 if (!$hist_clear_confirmed) {
916 # when clearing circ history, only warn if history data exists.
918 if ($clear_circ_history) {
920 if ($self->fetch_user_circ_history(0, 1)->[0]) {
921 $hist_warning_needed = 1;
922 next; # no history updates while confirmation pending
927 my $one_hold = $e->json_query({
931 transform => 'action.usr_visible_holds',
936 where => {id => $e->requestor->id},
941 $hist_warning_needed = 1;
942 next; # no history updates while confirmation pending
947 $settings{$key} = undef;
949 if ($key eq 'history.circ.retention_start') {
950 # delete existing circulation history data.
953 'open-ils.actor.history.circ.clear',
954 $self->editor->authtoken);
959 # Warn patrons before clearing circ/hold history
960 if ($hist_warning_needed) {
961 $self->ctx->{clear_circ_history} = $clear_circ_history;
962 $self->ctx->{clear_hold_history} = $clear_hold_history;
963 $self->ctx->{confirm_history_delete} = 1;
966 # Send the modified settings off to be saved
969 'open-ils.actor.patron.settings.update',
970 $self->editor->authtoken, undef, \%settings);
972 $self->ctx->{updated_user_settings} = \%settings;
974 if ($use_privacy_waiver) {
976 my $saved_entries = ();
977 my @waiver_types = qw/place_holds pickup_holds checkout_items view_history/;
979 # initialize our waiver hash with waiver IDs from hidden input
980 # (this ensures that we capture entries with no checked boxes)
981 foreach my $waiver_row_id ($self->cgi->param("waiver_id")) {
982 $waiver{$waiver_row_id} = {};
985 # process our waiver checkboxes into a hash, keyed by waiver ID
986 # (a new entry, if any, has id = 'new')
987 foreach my $waiver_type (@waiver_types) {
988 if ($self->cgi->param("waiver_$waiver_type")) {
989 foreach my $waiver_id ($self->cgi->param("waiver_$waiver_type")) {
990 # ensure this waiver exists in our hash
991 $waiver{$waiver_id} = {} if !$waiver{$waiver_id};
992 $waiver{$waiver_id}->{$waiver_type} = 1;
997 foreach my $k (keys %waiver) {
999 # get name from textbox
1000 $w->{name} = $self->cgi->param("waiver_name_$k");
1002 foreach (@waiver_types) {
1003 $w->{$_} = 0 unless ($w->{$_});
1005 push @$saved_entries, $w;
1008 # update patron privacy waiver entries
1011 'open-ils.actor.patron.privacy_waiver.update',
1012 $self->editor->authtoken, undef, $saved_entries);
1014 $self->ctx->{updated_waiver_entries} = $saved_entries;
1017 # re-fetch user prefs
1018 return $self->_load_user_with_prefs || Apache2::Const::OK;
1021 sub load_myopac_prefs_my_lists {
1024 my @user_prefs = qw/
1026 opac.list_items_per_page
1029 my $stat = $self->_load_user_with_prefs;
1030 return $stat if $stat;
1032 return Apache2::Const::OK
1033 unless $self->cgi->request_method eq 'POST';
1036 my $set_map = $self->ctx->{user_setting_map};
1038 foreach my $key (@user_prefs) {
1039 my $val = $self->cgi->param($key);
1040 $settings{$key}= $val unless $$set_map{$key} eq $val;
1043 if (keys %settings) { # we found a different setting value
1044 # Send the modified settings off to be saved
1047 'open-ils.actor.patron.settings.update',
1048 $self->editor->authtoken, undef, \%settings);
1050 # re-fetch user prefs
1051 $self->ctx->{updated_user_settings} = \%settings;
1052 $stat = $self->_load_user_with_prefs;
1055 return $stat || Apache2::Const::OK;
1058 sub fetch_user_holds {
1060 my $hold_ids = shift;
1061 my $ids_only = shift;
1063 my $available = shift;
1067 my $e = $self->editor;
1068 my $all_ids; # to be used below.
1071 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1073 $hold_ids = $circ->request(
1074 'open-ils.circ.holds.id_list.retrieve.authoritative',
1081 $all_ids = $hold_ids;
1082 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
1085 $all_ids = $hold_ids;
1088 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
1091 suppress_notices => 1,
1092 suppress_transits => 1,
1094 suppress_patron_details => 1
1097 # ----------------------------------------------------------------
1098 # Collect holds in batches of $batch_size for faster retrieval
1102 my $mk_req_batch = sub {
1104 my $top_idx = $batch_idx + $batch_size;
1105 while($batch_idx < $top_idx) {
1106 my $hold_id = $hold_ids->[$batch_idx++];
1107 last unless $hold_id;
1108 my $ses = OpenSRF::AppSession->create('open-ils.circ');
1109 my $req = $ses->request(
1110 'open-ils.circ.hold.details.retrieve',
1111 $e->authtoken, $hold_id, $args);
1112 push(@ses, {ses => $ses, req => $req});
1118 my(@collected, @holds, @ses);
1121 @ses = $mk_req_batch->() if $first;
1122 last if $first and not @ses;
1125 while(my $blob = pop(@collected)) {
1128 # in the holds edit UI, we need to know what formats and
1129 # languages the user selected for this hold, plus what
1130 # formats/langs are available on the MR as a whole.
1131 if ($blob->{hold}{hold}->hold_type eq 'M') {
1132 my $hold = $blob->{hold}->{hold};
1134 # for MR, fetch the combined MR unapi blob
1135 (undef, @data) = $self->get_records_and_facets(
1136 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
1138 my $filter_org = $U->org_unit_ancestor_at_depth(
1139 $hold->selection_ou,
1140 $hold->selection_depth);
1142 my $filter_data = $U->simplereq(
1144 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
1145 $hold->target, $filter_org, [$hold->id]
1148 $blob->{metarecord_filters} =
1149 $filter_data->[0]->{metarecord};
1150 $blob->{metarecord_selected_filters} =
1151 $filter_data->[1]->{hold};
1154 (undef, @data) = $self->get_records_and_facets(
1155 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
1159 $blob->{marc_xml} = $data[0]->{marc_xml};
1160 push(@holds, $blob);
1164 for my $req_data (@ses) {
1165 push(@collected, {hold => $req_data->{req}->gather(1)});
1166 $req_data->{ses}->kill_me;
1169 @ses = $mk_req_batch->();
1170 last unless @collected or @ses;
1174 # put the holds back into the original server sort order
1176 for my $id (@$hold_ids) {
1177 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1181 try { # if the service is not running, just let this fail silently
1182 $curbsides = $U->simplereq(
1183 'open-ils.curbside',
1184 'open-ils.curbside.fetch_mine.atomic',
1187 } catch Error with {};
1189 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, curbsides => $curbsides };
1192 sub load_current_curbside_libs {
1194 my $ctx = $self->ctx;
1195 my $e = $self->editor;
1196 my $holds = $e->search_action_hold_request({
1197 usr => $e->requestor->id,
1198 shelf_time => { '!=' => undef },
1199 cancel_time => undef,
1200 fulfillment_time => undef
1204 for my $h (@$holds) {
1205 next if ($h->pickup_lib != $h->current_shelf_lib);
1206 $pickup_libs{$h->pickup_lib} = 1;
1209 my @curbside_pickup_libs;
1210 for my $pul (keys %pickup_libs) {
1211 push(@curbside_pickup_libs, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1214 $ctx->{curbside_pickup_libs} = [
1215 sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } @curbside_pickup_libs
1219 sub handle_hold_update {
1222 my $hold_ids = shift;
1223 my $e = $self->editor;
1224 my $ctx = $self->ctx;
1227 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1228 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1230 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1232 if($action =~ /cancel/) {
1234 for my $hold_id (@hold_ids) {
1235 my $resp = $circ->request(
1236 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1239 } elsif ($action =~ /activate|suspend/) {
1242 for my $hold_id (@hold_ids) {
1243 my $vals = {id => $hold_id};
1245 if($action =~ /activate/) {
1246 $vals->{frozen} = 'f';
1247 $vals->{thaw_date} = undef;
1249 } elsif($action =~ /suspend/) {
1250 $vals->{frozen} = 't';
1251 # $vals->{thaw_date} = TODO;
1253 push(@$vlist, $vals);
1256 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1257 $self->ctx->{hold_suspend_post_capture} = 1 if
1258 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1260 } elsif ($action eq 'edit') {
1263 my $val = {"id" => $_};
1264 $val->{"frozen"} = $self->cgi->param("frozen");
1265 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1266 $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1267 $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1268 $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1269 $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1271 for my $field (qw/expire_time thaw_date/) {
1272 # XXX TODO make this support other date formats, not just
1274 next unless $self->cgi->param($field) =~
1275 m:^(\d{2})/(\d{2})/(\d{4})$:;
1276 $val->{$field} = "$3-$1-$2";
1279 $val->{holdable_formats} = # no-op for non-MR holds
1280 $self->compile_holdable_formats(undef, $_);
1286 'open-ils.circ.hold.update.batch.atomic',
1287 $e->authtoken, undef, \@vals
1288 )->gather(1); # LFW XXX test for failure
1289 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1290 foreach my $param (('loc', 'qtype', 'query')) {
1291 if ($self->cgi->param($param)) {
1292 my @vals = $self->cgi->param($param);
1293 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1296 } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1299 $circ = OpenSRF::AppSession->create('open-ils.curbside');
1301 # see what we're doing with curbside here...
1302 my $cs_action = $self->cgi->param("cs_action");
1303 my $slot_id = $self->cgi->param("cs_slot_id");
1305 # we have an id, let's grab it if we can
1306 my $slot = $e->retrieve_action_curbside($slot_id);
1307 $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1309 my $org = $self->cgi->param("cs_org");
1310 my $date = $self->cgi->param("cs_date");
1311 my $time = $self->cgi->param("cs_time");
1312 my $notes = $self->cgi->param("cs_notes");
1315 $org ||= $slot->org;
1316 $notes ||= $slot->notes;
1318 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1319 $date ||= $dt->strftime('%F');
1320 $time ||= $dt->strftime('%T');
1324 $ctx->{cs_org} = $org;
1325 $ctx->{cs_date} = $date;
1326 $ctx->{cs_time} = $time;
1327 $ctx->{cs_notes} = $notes;
1328 $ctx->{cs_slot_id} = $slot->id if ($slot);
1329 $ctx->{cs_slot} = $slot;
1331 if ($cs_action eq 'reset') {
1332 $ctx->{cs_org} = $org = undef;
1333 $ctx->{cs_date} = $date = undef;
1334 $ctx->{cs_time} = $time = undef;
1335 $ctx->{cs_notes} = $notes = undef;
1336 $ctx->{cs_slot_id} = $slot_id = undef;
1337 $ctx->{cs_slot} = $slot = undef;
1338 } elsif ($cs_action eq 'save' && $org && $date && $time) {
1339 my $mode = $slot ? 'update' : 'create';
1340 $slot = $circ->request(
1341 "open-ils.curbside.${mode}_appointment",
1342 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1345 if (defined $U->event_code($slot)) {
1346 $self->apache->log->warn(
1347 "error attempting to $mode a curbside appointment for patron ".
1348 $e->requestor->id . ", got event " . $slot->{textcode}
1350 $ctx->{curbside_action_event} = $slot;
1351 $ctx->{cs_slot} = undef;
1353 $ctx->{cs_slot} = $slot;
1355 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1356 } elsif ($cs_action eq 'cancel' && $slot) {
1357 my $curbsides = $U->simplereq(
1358 'open-ils.curbside',
1359 'open-ils.curbside.delete_appointment',
1360 $e->authtoken, $slot->id
1362 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1363 } elsif ($cs_action eq 'arrive' && $slot) {
1364 my $curbsides = $U->simplereq(
1365 'open-ils.curbside',
1366 'open-ils.curbside.mark_arrived',
1367 $e->authtoken, $slot->id
1369 } elsif ($cs_action eq 'deliver' && $slot) {
1370 my $curbsides = $U->simplereq(
1371 'open-ils.curbside',
1372 'open-ils.curbside.mark_delivered',
1373 $e->authtoken, $slot->id
1377 if ($date and $org and !$ctx->{cs_times}{$org}{$date}) {
1378 $ctx->{cs_times}{$org}{$date} = $circ->request(
1379 'open-ils.curbside.times_for_date.atomic',
1380 $e->authtoken, $date, $org
1386 return defined($url) ? $self->generic_redirect($url) : undef;
1389 sub load_myopac_holds {
1391 my $e = $self->editor;
1392 my $ctx = $self->ctx;
1394 my $limit = $self->cgi->param('limit') || 15;
1395 my $offset = $self->cgi->param('offset') || 0;
1396 my $action = $self->cgi->param('action') || '';
1397 my $hold_id = $self->cgi->param('hid');
1398 my $available = int($self->cgi->param('available') || 0);
1400 my $hold_handle_result;
1401 $hold_handle_result = $self->handle_hold_update($action) if $action;
1404 if ($self->cgi->param('sort') ne "") {
1405 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1408 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1411 if($holds_object->{holds}) {
1412 $ctx->{holds} = $holds_object->{holds};
1413 $ctx->{curbside_appointments} = {};
1415 $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1417 for my $cs (@{$holds_object->{curbsides}}) {
1419 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1420 $ctx->{cs_times}{$cs->org}{$dt} = $U->simplereq(
1421 'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1422 $e->authtoken, $dt, $cs->org
1425 $ctx->{curbside_appointments}{$cs->org} = $cs;
1428 $ctx->{holds_ids} = $holds_object->{all_ids};
1429 $ctx->{holds_limit} = $limit;
1430 $ctx->{holds_offset} = $offset;
1432 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1435 sub load_myopac_hold_subscriptions {
1437 my $e = $self->editor;
1438 my $ctx = $self->ctx;
1440 my $sub_remove = $self->cgi->param('remove');
1442 if ($sub_remove and $ctx->{user}->id) {
1443 my $sub_entries = $self->editor->search_container_user_bucket_item(
1444 { bucket => $sub_remove, target_user => $ctx->{user}->id }
1447 $self->editor->xact_begin;
1448 $self->editor->delete_container_user_bucket_item($_) for @$sub_entries;
1449 $self->editor->xact_commit;
1451 return $self->generic_redirect(
1452 $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/hold_subscriptions'
1456 return Apache2::Const::OK;
1461 sub load_place_hold {
1463 my $ctx = $self->ctx;
1464 my $gos = $ctx->{get_org_setting};
1465 my $e = $self->editor;
1466 my $cgi = $self->cgi;
1468 $self->ctx->{page} = 'place_hold';
1469 my @targets = uniq $cgi->param('hold_target');
1470 my @parts = $cgi->param('part');
1472 $ctx->{hold_subscription} = $cgi->param('hold_subscription');
1473 $ctx->{hold_type} = $cgi->param('hold_type');
1474 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1475 $ctx->{email_notify} = $cgi->param('email_notify');
1476 if ($cgi->param('phone_notify_checkbox')) {
1477 $ctx->{phone_notify} = $cgi->param('phone_notify');
1479 if ($cgi->param('sms_notify_checkbox')) {
1480 $ctx->{sms_notify} = $cgi->param('sms_notify');
1481 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1484 return $self->generic_redirect unless @targets;
1486 # Check for multiple hold placement via the num_copies widget.
1487 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1488 if ($num_copies > 1) {
1489 # Only if we have 1 hold target and no parts.
1490 if (scalar(@targets) == 1 && !$parts[0]) {
1491 # Also, only for M and T holds.
1492 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1493 # Add the extra holds to @targets. NOTE: We start with
1494 # 1 and go to < $num_copies to account for the
1496 for (my $i = 1; $i < $num_copies; $i++) {
1497 push(@targets, $targets[0]);
1503 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1505 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1510 au => ['settings', 'card']
1513 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1514 my $user_setting_map = {
1515 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1517 $ctx->{staff_recipient}->settings
1520 $ctx->{user_setting_map} = $user_setting_map;
1522 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1523 if ($default_notify =~ /email/) {
1524 $ctx->{default_email_notify} = 'checked';
1526 $ctx->{default_email_notify} = '';
1528 if ($default_notify =~ /phone/) {
1529 $ctx->{default_phone_notify} = 'checked';
1531 $ctx->{default_phone_notify} = '';
1533 if ($default_notify =~ /sms/) {
1534 $ctx->{default_sms_notify} = 'checked';
1536 $ctx->{default_sms_notify} = '';
1538 if ($cgi->param('hold_suspend')) {
1540 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1541 # We should use a date input type on the forms once it is supported by Firefox.
1542 # I didn't do that now because it is not available in a general release.
1543 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1545 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1546 $ctx->{thaw_date} = $dt->ymd;
1549 $logger->warn("ignoring invalid thaw_date when placing hold request");
1555 # If we have a default pickup location, grab it
1556 if ($$user_setting_map{'opac.default_pickup_location'}) {
1557 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1560 my $request_lib = $e->requestor->ws_ou;
1562 $ctx->{hold_data} = \@hold_data;
1564 $data_filler = sub {
1566 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1567 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1568 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1569 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1570 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1571 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1575 my $type_dispatch = {
1577 # target metarecords
1578 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1580 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1584 for my $id (@targets) {
1585 my ($mr) = grep {$_->id eq $id} @$mrecs;
1587 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1588 my $filter_data = $U->simplereq(
1590 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1592 my $holdable_formats =
1593 $self->compile_holdable_formats($mr->id);
1595 push(@hold_data, $data_filler->({
1597 record => $mr->master_record,
1598 holdable_formats => $holdable_formats,
1599 metarecord_filters => $filter_data->{metarecord}
1604 my $recs = $e->batch_retrieve_biblio_record_entry(
1605 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1609 for my $id (@targets) { # force back into the correct order
1610 my ($rec) = grep {$_->id eq $id} @$recs;
1612 # NOTE: if tpac ever supports locked-down pickup libs,
1613 # we'll need to pass a pickup_lib param along with the
1614 # record to filter the set of monographic parts.
1615 my $parts = $U->simplereq(
1617 'open-ils.search.biblio.record_hold_parts',
1618 {record => $rec->id}
1621 # T holds on records that have parts are OK, but if the record has
1622 # no non-part copies, the hold will ultimately fail. When that
1623 # happens, require the user to select a part.
1624 my $part_required = 0;
1626 my $np_copies = $e->json_query({
1627 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1628 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1630 '+acp' => {deleted => 'f'},
1631 '+acn' => {deleted => 'f', record => $rec->id},
1632 '+acpm' => {id => undef}
1635 $part_required = 1 if $np_copies->[0]->{count} == 0;
1638 push(@hold_data, $data_filler->({
1642 part_required => $part_required
1647 my $vols = $e->batch_retrieve_asset_call_number([
1650 "flesh_fields" => {"acn" => ["record"]}
1652 ], {substream => 1});
1654 for my $id (@targets) {
1655 my ($vol) = grep {$_->id eq $id} @$vols;
1656 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1660 my $copies = $e->batch_retrieve_asset_copy([
1664 "acn" => ["record"],
1665 "acp" => ["call_number"]
1668 ], {substream => 1});
1670 for my $id (@targets) {
1671 my ($copy) = grep {$_->id eq $id} @$copies;
1672 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1676 my $isses = $e->batch_retrieve_serial_issuance([
1680 "siss" => ["subscription"], "ssub" => ["record_entry"]
1683 ], {substream => 1});
1685 for my $id (@targets) {
1686 my ($iss) = grep {$_->id eq $id} @$isses;
1687 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1692 }->{$ctx->{hold_type}}->();
1694 # caller sent bad target IDs or the wrong hold type
1695 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1697 # generate the MARC xml for each record
1698 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1700 my $pickup_lib = $cgi->param('pickup_lib');
1701 # no pickup lib means no holds placement, except for subscriptions
1702 return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1704 $ctx->{hold_attempt_made} = 1;
1706 # Give the original CGI params back to the user in case they
1707 # want to try to override something.
1708 $ctx->{orig_params} = $cgi->Vars;
1709 delete $ctx->{orig_params}{submit};
1710 delete $ctx->{orig_params}{hold_target};
1711 delete $ctx->{orig_params}{part};
1713 my $usr = $e->requestor->id;
1715 if ($ctx->{is_staff}) {
1716 $logger->info("Staff initiated hold");
1717 if (!$cgi->param("hold_usr_is_requestor")) {
1718 # find the real hold target
1720 $usr = $U->simplereq(
1722 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1723 $e->authtoken, $cgi->param("hold_usr"));
1725 if (defined $U->event_code($usr)) {
1726 $ctx->{hold_failed} = 1;
1727 $ctx->{hold_failed_event} = $usr;
1731 if ($ctx->{hold_subscription}) {
1732 # this is a batch event, hold "user" is a bucket id
1733 $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1734 $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1738 # target_id is the true target_id for holds placement.
1739 # needed for attempt_hold_placement()
1740 # With the exception of P-type holds, target_id == target->id.
1741 $_->{target_id} = $_->{target}->id for @hold_data;
1743 if ($ctx->{hold_type} eq 'T') {
1745 # Much like quantum wave-particles, P-type holds pop into
1746 # and out of existence at the user's whim. For our purposes,
1747 # we treat such holds as T(itle) holds with a selected_part
1748 # designation. When the time comes to pass the hold information
1749 # off for holds possibility testing and placement, make it look
1750 # like a real P-type hold.
1751 my (@p_holds, @t_holds);
1753 # Now that we have the num_copies field for mutliple title and
1754 # metarecord hold placement, the number of holds and parts
1755 # arrays can get out of sync. We only want to parse out parts
1756 # if the numbers are equal.
1757 if ($#hold_data == $#parts) {
1758 for my $idx (0..$#parts) {
1759 my $hdata = $hold_data[$idx];
1760 if (my $part = $parts[$idx]) {
1761 $hdata->{target_id} = $part;
1762 $hdata->{selected_part} = $part;
1763 push(@p_holds, $hdata);
1765 push(@t_holds, $hdata);
1769 @t_holds = @hold_data;
1772 $self->apache->log->warn("$#parts : @t_holds");
1774 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1775 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1778 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1781 # NOTE: we are leaving the staff-placed patron barcode cookie
1782 # in place. Otherwise, it's not possible to place more than
1783 # one hold for the patron within a staff/patron session. This
1784 # does leave the barcode to linger longer than is ideal, but
1785 # normal staff work flow will cause the cookie to be replaced
1786 # with each new patron anyway.
1787 # TODO: See about getting the staff client to clear the cookie
1789 # return to the place_hold page so the results of the hold
1790 # placement attempt can be reported to the user
1791 return Apache2::Const::OK;
1794 sub attempt_hold_placement {
1795 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1796 my $cgi = $self->cgi;
1797 my $ctx = $self->ctx;
1798 my $e = $self->editor;
1800 my $user_container = undef;
1801 if (ref($usr)) { # $usr is actually a container for a subscription...
1802 $user_container = $usr->id;
1803 return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1806 # First see if we should warn/block for any holds that
1807 # might have locally available items for non-subscriptions.
1808 if (!$user_container) {
1809 for my $hdata (@hold_data) {
1810 my ($local_block, $local_alert) = $self->local_avail_concern(
1811 $hdata->{target_id}, $hold_type, $pickup_lib);
1814 $hdata->{hold_failed} = 1;
1815 $hdata->{hold_local_block} = 1;
1816 } elsif ($local_alert) {
1817 $hdata->{hold_failed} = 1;
1818 $hdata->{hold_local_alert} = 1;
1823 my $method = $user_container
1824 ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1825 : 'open-ils.circ.holds.test_and_create.batch';
1827 if ($cgi->param('override')) {
1828 $method .= '.override';
1830 } elsif (!$ctx->{is_staff}) {
1832 $method .= '.override' if $self->ctx->{get_org_setting}->(
1833 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1836 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1839 if(@create_targets) {
1841 # holdable formats may be different for each MR hold.
1842 # map each set to the ID of the target.
1843 my $holdable_formats = {};
1844 if ($hold_type eq 'M') {
1845 $holdable_formats->{$_->{target_id}} =
1846 $_->{holdable_formats} for @hold_data;
1849 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1851 my @create_params = ();
1853 if ($user_container) {
1856 hold_type => $hold_type,
1857 holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1866 pickup_lib => $pickup_lib,
1867 hold_type => $hold_type,
1868 holdable_formats_map => $holdable_formats,
1874 my $breq = $bses->request($method, $e->authtoken, @create_params);
1876 while (my $resp = $breq->recv) {
1878 $resp = $resp->content;
1879 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1881 if ($U->event_code($resp)) {
1882 $ctx->{general_hold_error} = $resp;
1886 # subscription batch create sends an initial response to assist with client-side counting
1889 defined($$resp{count}) and $$resp{count} == 0
1890 and defined($$resp{total}) and $$resp{total} > 0
1893 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1894 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1895 my $result = $resp->{result};
1897 if ($U->event_code($result)) {
1898 # e.g. permission denied
1899 $hdata->{hold_failed} = 1;
1900 $hdata->{hold_failed_event} = $result;
1904 if(not ref $result and $result > 0) {
1905 # successul hold returns the hold ID
1906 $hdata->{hold_success} = $result;
1909 # hold-specific failure event
1910 $hdata->{hold_failed} = 1;
1912 if (ref $result eq 'HASH') {
1913 $hdata->{hold_failed_event} = $result->{last_event};
1915 if ($result->{age_protected_copy}) {
1916 my %temp = %{$hdata->{hold_failed_event}};
1917 my $theTextcode = $temp{"textcode"};
1918 $theTextcode.=".override";
1919 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1920 $hdata->{age_protect} = 1;
1922 $hdata->{could_override} = $result->{place_unfillable} ||
1923 $self->test_could_override($hdata->{hold_failed_event});
1925 } elsif (ref $result eq 'ARRAY') {
1926 $hdata->{hold_failed_event} = $result->[0];
1928 if ($result->[3]) { # age_protect_only
1929 my %temp = %{$hdata->{hold_failed_event}};
1930 my $theTextcode = $temp{"textcode"};
1931 $theTextcode.=".override";
1932 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1933 $hdata->{age_protect} = 1;
1935 $hdata->{could_override} = $result->[4] || # place_unfillable
1936 $self->test_could_override($hdata->{hold_failed_event});
1946 if ($self->cgi->param('clear_cart')) {
1947 $self->clear_anon_cache;
1951 # pull the selected formats and languages for metarecord holds
1952 # from the CGI params and map them into the JSON holdable
1953 # formats...er, format.
1954 # if no metarecord is provided, we'll pull it from the target
1955 # of the provided hold.
1956 sub compile_holdable_formats {
1957 my ($self, $mr_id, $hold_id) = @_;
1958 my $e = $self->editor;
1959 my $cgi = $self->cgi;
1961 # exit early if not needed
1963 grep /metarecord_formats_|metarecord_langs_/,
1966 # CGI params are based on the MR id, since during hold placement
1967 # we have no old ID. During hold edit, map the hold ID back to
1968 # the metarecod target.
1970 $e->retrieve_action_hold_request($hold_id)->target
1973 my $format_attr = $self->ctx->{get_cgf}->(
1974 'opac.metarecord.holds.format_attr');
1976 if (!$format_attr) {
1977 $logger->error("Missing config.global_flag: ".
1978 "opac.metarecord.holds.format_attr!");
1982 $format_attr = $format_attr->value;
1984 # during hold placement or edit submission, the user selects
1985 # which of the available formats/langs are acceptable.
1986 # Capture those here as the holdable_formats for the MR hold.
1987 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1988 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1990 # map the selected attrs into the JSON holdable_formats structure
1992 if (@selected_formats) {
1994 map { {_attr => $format_attr, _val => $_} }
1998 if (@selected_langs) {
2000 map { {_attr => 'item_lang', _val => $_} }
2005 return OpenSRF::Utils::JSON->perl2JSON($blob);
2008 sub fetch_user_circs {
2010 my $flesh = shift; # flesh bib data, etc.
2011 my $circ_ids = shift;
2015 my $e = $self->editor;
2020 @circ_ids = @$circ_ids;
2025 select => {circ => ['id']},
2029 usr => $e->requestor->id,
2030 checkin_time => undef,
2032 {stop_fines => undef},
2033 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2037 order_by => {circ => ['due_date']}
2040 $query->{limit} = $limit if $limit;
2041 $query->{offset} = $offset if $offset;
2043 my $ids = $e->json_query($query);
2044 @circ_ids = map {$_->{id}} @$ids;
2047 return [] unless @circ_ids;
2052 circ => ['target_copy'],
2053 acp => ['call_number','parts'],
2054 acn => ['record','owning_lib','prefix','suffix']
2059 my $circs = $e->search_action_circulation(
2060 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2063 for my $circ (@$circs) {
2066 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2067 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2068 undef # pre-cat copy, use the dummy title/author instead
2073 # make sure the final list is in the correct order
2075 for my $id (@circ_ids) {
2078 (grep { $_->{circ}->id == $id } @circs)
2082 return \@sorted_circs;
2086 sub handle_circ_renew {
2089 my $ctx = $self->ctx;
2091 my @renew_ids = $self->cgi->param('circ');
2093 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2095 # TODO: fire off renewal calls in batches to speed things up
2097 for my $circ (@$circs) {
2099 my $evt = $U->simplereq(
2101 'open-ils.circ.renew',
2102 $self->editor->authtoken,
2104 patron_id => $self->editor->requestor->id,
2105 copy_id => $circ->{circ}->target_copy,
2110 # TODO return these, then insert them into the circ data
2111 # blob that is shoved into the template for each circ
2112 # so the template won't have to match them
2113 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2119 sub load_myopac_circs {
2121 my $e = $self->editor;
2122 my $ctx = $self->ctx;
2125 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2126 my $offset = $self->cgi->param('offset') || 0;
2127 my $action = $self->cgi->param('action') || '';
2129 # perform the renewal first if necessary
2130 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2132 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2134 my $success_renewals = 0;
2135 my $failed_renewals = 0;
2136 for my $data (@{$ctx->{circs}}) {
2137 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2140 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2142 # extract the fail_part, if present, from the event payload;
2143 # since # the payload is an acp object in some cases,
2144 # blindly looking for a # 'fail_part' key in the template can
2146 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2147 $evt->{payload}->{fail_part} :
2150 $data->{renewal_response} = $evt;
2151 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2152 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2156 $ctx->{success_renewals} = $success_renewals;
2157 $ctx->{failed_renewals} = $failed_renewals;
2159 return Apache2::Const::OK;
2162 sub load_myopac_circ_history {
2164 my $e = $self->editor;
2165 my $ctx = $self->ctx;
2166 my $limit = $self->cgi->param('limit') || 15;
2167 my $offset = $self->cgi->param('offset') || 0;
2168 my $action = $self->cgi->param('action') || '';
2170 my $circ_handle_result;
2171 $circ_handle_result = $self->handle_circ_update($action) if $action;
2173 $ctx->{circ_history_limit} = $limit;
2174 $ctx->{circ_history_offset} = $offset;
2176 # Defer limitation to circ_history.tt2 when sorting
2177 if ($self->cgi->param('sort')) {
2182 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2183 return Apache2::Const::OK;
2186 # if 'flesh' is set, copy data etc. is loaded and the return value is
2187 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2189 sub fetch_user_circ_history {
2190 my ($self, $flesh, $limit, $offset) = @_;
2191 my $e = $self->editor;
2194 $limits{offset} = $offset if defined $offset;
2195 $limits{limit} = $limit if defined $limit;
2200 auch => ['target_copy','source_circ'],
2201 acp => ['call_number','parts'],
2202 acn => ['record','prefix','suffix']
2207 my $circs = $e->search_action_user_circ_history(
2209 {usr => $e->requestor->id},
2210 { # order newest to oldest by default
2211 order_by => {auch => 'xact_start DESC'},
2212 $flesh ? %flesh_ops : (),
2220 return $circs unless $flesh;
2224 my %unapi_cache = ();
2225 for my $circ (@$circs) {
2226 if ($circ->target_copy->call_number->id == -1) {
2229 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2233 my $bre_id = $circ->target_copy->call_number->record->id;
2235 if (exists $unapi_cache{$bre_id}) {
2236 $unapi = $unapi_cache{$bre_id};
2238 my $result = $e->json_query({
2240 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2244 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2255 marc_xml => undef # failed, but try to go on
2264 sub handle_circ_update {
2267 my $circ_ids = shift;
2269 $circ_ids //= [$self->cgi->param('circ_id')];
2271 if ($action =~ /delete/) {
2273 circ_ids => $circ_ids,
2278 'open-ils.actor.history.circ.clear',
2279 $self->editor->authtoken,
2287 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2288 sub load_myopac_hold_history {
2290 my $e = $self->editor;
2291 my $ctx = $self->ctx;
2292 my $limit = $self->cgi->param('limit') || 15;
2293 my $offset = $self->cgi->param('offset') || 0;
2294 $ctx->{hold_history_limit} = $limit;
2295 $ctx->{hold_history_offset} = $offset;
2297 my $hold_ids = $e->json_query({
2301 transform => 'action.usr_visible_holds',
2302 result_field => 'id'
2306 where => {id => $e->requestor->id}
2309 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2310 if($holds_object->{holds}) {
2311 $ctx->{holds} = $holds_object->{holds};
2313 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2315 return Apache2::Const::OK;
2318 sub load_myopac_payment_form {
2321 my $e = $self->editor;
2323 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2325 if ( ! $self->cgi->param('last_chance') # only do this once
2326 && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')
2327 && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2328 my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2329 my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2330 my $stripe = Business::Stripe->new(-api_key => $skey);
2331 my $intent = $stripe->api('post', 'payment_intents',
2332 amount => $self->ctx->{fines}->{balance_owed} * 100,
2333 currency => $currency || 'usd'
2335 if ($stripe->success) {
2336 $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2338 $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2339 $self->ctx->{cc_configuration_error} = 1;
2343 if ($r) { return $r; }
2344 $r = $self->prepare_extended_user_info and return $r;
2346 return Apache2::Const::OK;
2349 # TODO: add other filter options as params/configs/etc.
2350 sub load_myopac_payments {
2352 my $limit = $self->cgi->param('limit') || 20;
2353 my $offset = $self->cgi->param('offset') || 0;
2354 my $e = $self->editor;
2356 $self->ctx->{payment_history_limit} = $limit;
2357 $self->ctx->{payment_history_offset} = $offset;
2360 $args->{limit} = $limit if $limit;
2361 $args->{offset} = $offset if $offset;
2363 if (my $max_age = $self->ctx->{get_org_setting}->(
2364 $e->requestor->home_ou, "opac.payment_history_age_limit"
2366 my $min_ts = DateTime->now(
2367 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2368 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2370 $logger->info("XXX min_ts: $min_ts");
2371 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2374 $self->ctx->{payments} = $U->simplereq(
2376 'open-ils.actor.user.payments.retrieve.atomic',
2377 $e->authtoken, $e->requestor->id, $args);
2379 return Apache2::Const::OK;
2382 # 1. caches the form parameters
2383 # 2. loads the credit card payment "Processing..." page
2384 sub load_myopac_pay_init {
2386 my $cache = OpenSRF::Utils::Cache->new('global');
2388 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2390 if (!@payment_xacts) {
2391 # for consistency with load_myopac_payment_form() and
2392 # to preserve backwards compatibility, if no xacts are
2393 # selected, assume all (applicable) transactions are wanted.
2394 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2395 return $stat if $stat;
2397 map { $_->{xact}->id } (
2398 @{$self->ctx->{fines}->{circulation}},
2399 @{$self->ctx->{fines}->{grocery}}
2403 return $self->generic_redirect unless @payment_xacts;
2405 my $cc_args = {"where_process" => 1};
2407 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2408 number cvv2 expire_year expire_month billing_first
2409 billing_last billing_address billing_city billing_state
2410 billing_zip stripe_payment_intent stripe_client_secret
2414 cc_args => $cc_args,
2415 user => $self->ctx->{user}->id,
2416 xacts => \@payment_xacts
2419 # generate a temporary cache token and cache the form data
2420 my $token = md5_hex($$ . time() . rand());
2421 $cache->put_cache($token, $cache_args, 30);
2423 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2425 # after we render the processing page, we quickly redirect to submit
2426 # the actual payment. The refresh url contains the payment token.
2427 # It also contains the list of xact IDs, which allows us to clear the
2428 # cache at the earliest possible time while leaving a trace of which
2429 # transactions we were processing, so the UI can bring the user back
2430 # to the payment form w/ the same xacts if the payment fails.
2432 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2433 $refresh .= ";xact=$_" for @payment_xacts;
2434 $self->ctx->{refresh} = $refresh;
2436 return Apache2::Const::OK;
2439 # retrieve the cached CC payment info and send off for processing
2440 sub load_myopac_pay {
2442 my $token = $self->ctx->{page_args}->[0];
2443 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2445 my $cache = OpenSRF::Utils::Cache->new('global');
2446 my $cache_args = $cache->get_cache($token);
2447 $cache->delete_cache($token);
2449 # this page is loaded immediately after the token is created.
2450 # if the cached data is not there, it's because of an invalid
2451 # token (or cache failure) and not because of a timeout.
2452 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2454 my @payment_xacts = @{$cache_args->{xacts}};
2455 my $cc_args = $cache_args->{cc_args};
2457 # as an added security check, verify the user submitting
2458 # the form is the same as the user whose data was cached
2459 return Apache2::Const::HTTP_BAD_REQUEST unless
2460 $cache_args->{user} == $self->ctx->{user}->id;
2462 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2465 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2467 # balance_owed is computed specifically from the fines we're paying
2468 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2469 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2470 return Apache2::Const::HTTP_BAD_REQUEST;
2474 "cc_args" => $cc_args,
2475 "userid" => $self->ctx->{user}->id,
2476 "payment_type" => "credit_card_payment",
2477 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2480 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2481 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2484 $self->ctx->{"payment_response"} = $resp;
2486 unless ($resp->{"textcode"}) {
2487 $self->ctx->{printable_receipt} = $U->simplereq(
2488 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2489 $self->editor->authtoken, $resp->{payments}
2493 return Apache2::Const::OK;
2496 sub load_myopac_receipt_print {
2499 $self->ctx->{printable_receipt} = $U->simplereq(
2500 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2501 $self->editor->authtoken, [$self->cgi->param("payment")]
2504 return Apache2::Const::OK;
2507 sub load_myopac_receipt_email {
2510 # The following ML method doesn't actually check whether the user in
2511 # question has an email address, so we do.
2512 if ($self->ctx->{user}->email) {
2513 $self->ctx->{email_receipt_result} = $U->simplereq(
2514 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2515 $self->editor->authtoken, [$self->cgi->param("payment")]
2518 $self->ctx->{email_receipt_result} =
2519 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2522 return Apache2::Const::OK;
2526 my ($self, $limit, $offset, $id_list) = @_;
2528 # XXX TODO: check for failure after various network calls
2530 # It may be unclear, but this result structure lumps circulation and
2531 # reservation fines together, and keeps grocery fines separate.
2532 $self->ctx->{"fines"} = {
2533 "circulation" => [],
2540 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2542 # TODO: This should really be a ML call, but the existing calls
2543 # return an excessive amount of data and don't offer streaming
2545 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2547 my $req = $cstore->request(
2548 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2550 usr => $self->editor->requestor->id,
2551 balance_owed => {'!=' => 0},
2552 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2557 mobts => [qw/grocery circulation reservation/],
2558 bresv => ['target_resource_type'],
2562 circ => ['target_copy'],
2563 acp => ['call_number'],
2566 order_by => { mobts => 'xact_start' },
2571 # Collect $$ amounts from each transaction for summing below.
2572 my (@paid_amounts, @owed_amounts, @balance_amounts);
2574 while(my $resp = $req->recv) {
2575 my $mobts = $resp->content;
2576 my $circ = $mobts->circulation;
2579 if($mobts->grocery) {
2580 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2581 $last_billing = pop(@billings);
2584 push(@paid_amounts, $mobts->total_paid);
2585 push(@owed_amounts, $mobts->total_owed);
2586 push(@balance_amounts, $mobts->balance_owed);
2588 my $marc_xml = undef;
2589 if ($mobts->xact_type eq 'reservation' and
2590 $mobts->reservation->target_resource_type->record) {
2591 $marc_xml = XML::LibXML->new->parse_string(
2592 $mobts->reservation->target_resource_type->record->marc
2594 } elsif ($mobts->xact_type eq 'circulation' and
2595 $circ->target_copy->call_number->id != -1) {
2596 $marc_xml = XML::LibXML->new->parse_string(
2597 $circ->target_copy->call_number->record->marc
2602 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2605 last_grocery_billing => $last_billing,
2606 marc_xml => $marc_xml
2613 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2614 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2615 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2620 sub prepare_fines_for_payment {
2621 # This assumes $self->prepare_fines has already been run
2625 if ($self->ctx->{fines}) {
2626 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2627 @{$self->ctx->{fines}->{circulation}},
2628 @{$self->ctx->{fines}->{grocery}}
2635 sub load_myopac_main {
2637 my $limit = $self->cgi->param('limit') || 0;
2638 my $offset = $self->cgi->param('offset') || 0;
2639 $self->ctx->{search_ou} = $self->_get_search_lib();
2640 $self->ctx->{user}->notes(
2641 $self->editor->search_actor_usr_message({
2642 usr => $self->ctx->{user}->id,
2646 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2649 sub load_myopac_update_email {
2651 my $e = $self->editor;
2652 my $ctx = $self->ctx;
2653 my $email = $self->cgi->param('email') || '';
2654 my $current_pw = $self->cgi->param('current_pw') || '';
2656 # needed for most up-to-date email address
2657 if (my $r = $self->prepare_extended_user_info) { return $r };
2659 return Apache2::Const::OK
2660 unless $self->cgi->request_method eq 'POST';
2662 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2663 $ctx->{invalid_email} = $email;
2664 return Apache2::Const::OK;
2667 my $stat = $U->simplereq(
2669 'open-ils.actor.user.email.update',
2670 $e->authtoken, $email, $current_pw);
2672 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2673 $ctx->{password_incorrect} = 1;
2674 return Apache2::Const::OK;
2677 unless ($self->cgi->param("redirect_to")) {
2678 my $url = $self->apache->unparsed_uri;
2679 $url =~ s/update_email/prefs/;
2681 return $self->generic_redirect($url);
2684 return $self->generic_redirect;
2687 sub load_myopac_update_username {
2689 my $e = $self->editor;
2690 my $ctx = $self->ctx;
2691 my $username = $self->cgi->param('username') || '';
2692 my $current_pw = $self->cgi->param('current_pw') || '';
2694 $self->prepare_extended_user_info;
2696 my $allow_change = 1;
2698 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2699 if(defined($lock_usernames) and $lock_usernames == 1) {
2700 # Policy says no username changes
2703 # We want this further down.
2704 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2705 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2706 if(!$username_unlimit) {
2708 # Default is "starts with a number"
2709 $regex_check = '^\d+';
2711 # You already have a username?
2712 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2717 if(!$allow_change) {
2718 my $url = $self->apache->unparsed_uri;
2719 $url =~ s/update_username/prefs/;
2721 return $self->generic_redirect($url);
2724 return Apache2::Const::OK
2725 unless $self->cgi->request_method eq 'POST';
2727 unless($username and $username !~ /\s/) { # any other username restrictions?
2728 $ctx->{invalid_username} = $username;
2729 return Apache2::Const::OK;
2732 # New username can't look like a barcode if we have a barcode regex
2733 if($regex_check and $username =~ /$regex_check/) {
2734 $ctx->{invalid_username} = $username;
2735 return Apache2::Const::OK;
2738 # New username has to look like a username if we have a username regex
2739 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2740 if($regex_check and $username !~ /$regex_check/) {
2741 $ctx->{invalid_username} = $username;
2742 return Apache2::Const::OK;
2745 if($username ne $e->requestor->usrname) {
2747 my $evt = $U->simplereq(
2749 'open-ils.actor.user.username.update',
2750 $e->authtoken, $username, $current_pw);
2752 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2753 $ctx->{password_incorrect} = 1;
2754 return Apache2::Const::OK;
2757 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2758 $ctx->{username_exists} = $username;
2759 return Apache2::Const::OK;
2763 my $url = $self->apache->unparsed_uri;
2764 $url =~ s/update_username/prefs/;
2766 return $self->generic_redirect($url);
2769 sub load_myopac_update_password {
2771 my $e = $self->editor;
2772 my $ctx = $self->ctx;
2774 return Apache2::Const::OK
2775 unless $self->cgi->request_method eq 'POST';
2777 my $current_pw = $self->cgi->param('current_pw') || '';
2778 my $new_pw = $self->cgi->param('new_pw') || '';
2779 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2781 unless($new_pw eq $new_pw2) {
2782 $ctx->{password_nomatch} = 1;
2783 return Apache2::Const::OK;
2786 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2789 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2790 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2793 if($pw_regex and $new_pw !~ /$pw_regex/) {
2794 $ctx->{password_invalid} = 1;
2795 return Apache2::Const::OK;
2798 my $evt = $U->simplereq(
2800 'open-ils.actor.user.password.update',
2801 $e->authtoken, $new_pw, $current_pw);
2804 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2805 $ctx->{password_incorrect} = 1;
2806 return Apache2::Const::OK;
2809 my $url = $self->apache->unparsed_uri;
2810 $url =~ s/update_password/prefs/;
2812 return $self->generic_redirect($url);
2815 sub _update_bookbag_metadata {
2816 my ($self, $bookbag) = @_;
2818 $bookbag->name($self->cgi->param("name"));
2819 $bookbag->description($self->cgi->param("description"));
2821 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2825 sub _get_lists_per_page {
2828 if($self->editor->requestor) {
2829 $self->timelog("Checking for opac.lists_per_page preference");
2830 # See if the user has a lists per page preference
2831 my $ipp = $self->editor->search_actor_user_setting({
2832 usr => $self->editor->requestor->id,
2833 name => 'opac.lists_per_page'
2835 $self->timelog("Got opac.lists_per_page preference");
2836 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2838 return 10; # default
2841 sub _get_items_per_page {
2844 if($self->editor->requestor) {
2845 $self->timelog("Checking for opac.list_items_per_page preference");
2846 # See if the user has a list items per page preference
2847 my $ipp = $self->editor->search_actor_user_setting({
2848 usr => $self->editor->requestor->id,
2849 name => 'opac.list_items_per_page'
2851 $self->timelog("Got opac.list_items_per_page preference");
2852 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2854 return 10; # default
2857 sub load_myopac_bookbags {
2859 my $e = $self->editor;
2860 my $ctx = $self->ctx;
2861 my $limit = $self->_get_lists_per_page || 10;
2862 my $offset = $self->cgi->param('offset') || 0;
2864 $ctx->{bookbags_limit} = $limit;
2865 $ctx->{bookbags_offset} = $offset;
2867 # for list item pagination
2868 my $item_limit = $self->_get_items_per_page;
2869 my $item_page = $self->cgi->param('item_page') || 1;
2870 my $item_offset = ($item_page - 1) * $item_limit;
2871 $ctx->{bookbags_item_page} = $item_page;
2873 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2874 $e->xact_begin; # replication...
2876 my $rv = $self->load_mylist;
2877 unless($rv eq Apache2::Const::OK) {
2882 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2884 {owner => $e->requestor->id, btype => 'bookbag'}, {
2885 order_by => {cbreb => 'name'},
2893 if(!$ctx->{bookbags}) {
2895 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2898 # We load the user prefs to get their default bookbag.
2899 $self->_load_user_with_prefs;
2901 # We also want a total count of the user's bookbags.
2903 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2905 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2907 my $r = $e->json_query($q);
2908 $ctx->{bookbag_count} = $r->[0]->{'count'};
2910 # If the user wants a specific bookbag's items, load them.
2912 if ($self->cgi->param("bbid")) {
2914 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2917 my $query = $self->_prepare_bookbag_container_query(
2918 $bookbag->id, $sorter, $modifier
2921 # Calculate total count of the items in selected bookbag.
2922 # This total includes record entries that have no assets available.
2923 my $bb_search_results = $U->simplereq(
2924 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2925 {"limit" => 1, "offset" => 0}, $query
2926 ); # we only need the count, so do the actual search with limit=1
2928 if ($bb_search_results) {
2929 $ctx->{bb_item_count} = $bb_search_results->{count};
2931 $logger->warn("search failed in load_myopac_bookbags()");
2932 $ctx->{bb_item_count} = 0; # fallback value
2935 #calculate page count
2936 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2938 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2939 if (!$self->_update_bookbag_metadata($bookbag)) {
2941 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2944 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2947 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2948 if ($self->cgi->param($param)) {
2949 my @vals = $self->cgi->param($param);
2950 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2954 return $self->generic_redirect($url);
2958 # we're done with our CStoreEditor. Rollback here so
2959 # later calls don't cause a timeout, resulting in a
2960 # transaction rollback under the covers.
2964 # For list items pagination
2966 "limit" => $item_limit,
2967 "offset" => $item_offset
2970 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2971 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2973 # capture pref_ou for callnumber filter/display
2974 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2976 # search for local callnumbers for display
2977 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2979 my (undef, @recs) = $self->get_records_and_facets(
2980 [ map {$_->target_biblio_record_entry->id} @$items ],
2983 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2985 site => $ctx->{get_aou}->($focus_ou)->shortname,
2986 pref_lib => $ctx->{pref_ou}
2990 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2992 $bookbag->items($items);
2996 # If we have add_rec, we got here from the "Add to new list"
2997 # or "See all" popmenu items.
2998 if (my $add_rec = $self->cgi->param('add_rec')) {
2999 $self->ctx->{add_rec} = $add_rec;
3000 # But not in the staff client, 'cause that breaks things.
3001 unless ($self->ctx->{is_staff}) {
3002 # allow caller to provide the where_from in cases where
3003 # the referer is an intermediate error page
3004 if ($self->cgi->param('where_from')) {
3005 $self->ctx->{where_from} = $self->cgi->param('where_from');
3007 $self->ctx->{where_from} = $self->ctx->{referer};
3008 if ( my $anchor = $self->cgi->param('anchor') ) {
3009 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3015 # this rollback may be a dupe, but that's OK because
3016 # cstoreditor ignores dupe rollbacks
3019 return Apache2::Const::OK;
3023 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3024 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3025 sub load_myopac_bookbag_update {
3026 my ($self, $action, $list_id, @hold_recs) = @_;
3027 my $e = $self->editor;
3028 my $cgi = $self->cgi;
3030 # save_notes is effectively another action, but is passed in a separate
3031 # CGI parameter for what are really just layout reasons.
3032 $action = 'save_notes' if $cgi->param('save_notes');
3033 $action ||= $cgi->param('action');
3035 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3037 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3038 my @selected_item = $cgi->param('selected_item');
3039 my $shared = $cgi->param('shared');
3040 my $move_cart = $cgi->param('move_cart');
3041 my $name = $cgi->param('name');
3042 my $description = $cgi->param('description');
3046 # bail out if user is attempting an action that requires
3047 # that at least one list item be selected
3048 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3049 ($action eq 'place_hold' || $action eq 'print' ||
3050 $action eq 'email' || $action eq 'del_item')) {
3051 my $url = $self->ctx->{referer};
3052 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3053 return $self->generic_redirect($url);
3056 # This url intentionally leaves off the edit_notes parameter, but
3057 # may need to add some back in for paging.
3059 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3060 $self->ctx->{opac_root} . "/myopac/lists?";
3062 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3063 if ($cgi->param($param)) {
3064 my @vals = $cgi->param($param);
3065 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3069 if ($action eq 'create') {
3072 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3074 $list->description($description);
3075 $list->owner($e->requestor->id);
3076 $list->btype('bookbag');
3077 $list->pub($shared ? 't' : 'f');
3078 $success = $U->simplereq('open-ils.actor',
3079 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3080 if (ref($success) ne 'HASH') {
3081 $list_id = (ref($success)) ? $success->id : $success;
3082 if (scalar @add_rec) {
3083 foreach my $add_rec (@add_rec) {
3084 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3085 $item->bucket($list_id);
3086 $item->target_biblio_record_entry($add_rec);
3087 $success = $U->simplereq('open-ils.actor',
3088 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3089 last unless $success;
3093 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3094 foreach my $add_rec (@$list) {
3095 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3096 $item->bucket($list_id);
3097 $item->target_biblio_record_entry($add_rec);
3098 $success = $U->simplereq('open-ils.actor',
3099 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3100 last unless $success;
3102 $self->clear_anon_cache;
3105 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3108 $self->ctx->{bucket_failure_noname} = 1;
3111 } elsif($action eq 'place_hold') {
3113 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3114 my $from_basket = scalar(@hold_recs);
3115 unless (@hold_recs) {
3116 if (@selected_item) {
3117 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3118 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3122 return Apache2::Const::OK unless @hold_recs;
3123 $logger->info("placing holds from list page on: @hold_recs");
3125 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3126 $url .= ';hold_target=' . $_ for @hold_recs;
3127 $url .= ';from_basket=1' if $from_basket;
3128 foreach my $param (('loc', 'qtype', 'query')) {
3129 if ($cgi->param($param)) {
3130 my @vals = $cgi->param($param);
3131 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3134 return $self->generic_redirect($url);
3136 } elsif ($action eq 'print') {
3137 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3138 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3139 if (!$incoming_sort) {
3140 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3142 if (!$incoming_sort) {
3143 $incoming_sort = 'author';
3146 $incoming_sort =~ s/sort.*$//;
3148 $self->ctx->{sort} = $incoming_sort;
3149 $self->ctx->{sort_dir} = $sort_dir;
3151 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3152 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3153 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3154 return $self->load_mylist_print($temp_cache_key);
3155 } elsif ($action eq 'email') {
3156 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3157 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3158 if (!$incoming_sort) {
3159 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3161 if (!$incoming_sort) {
3162 $incoming_sort = 'author';
3165 $incoming_sort =~ s/sort.*$//;
3167 $self->ctx->{sort} = $incoming_sort;
3168 $self->ctx->{sort_dir} = $sort_dir;
3170 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3171 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3172 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3173 return $self->load_mylist_email($temp_cache_key);
3176 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3178 return Apache2::Const::HTTP_BAD_REQUEST unless
3179 $list and $list->owner == $e->requestor->id;
3182 if($action eq 'delete') {
3183 $success = $U->simplereq('open-ils.actor',
3184 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3186 # We check to see if we're deleting the user's default list.
3187 $self->_load_user_with_prefs;
3188 my $settings_map = $self->ctx->{user_setting_map};
3189 if ($$settings_map{'opac.default_list'} == $list_id) {
3190 # We unset the user's opac.default_list setting.
3191 $success = $U->simplereq(
3193 'open-ils.actor.patron.settings.update',
3196 { 'opac.default_list' => 0 }
3200 } elsif($action eq 'show') {
3201 unless($U->is_true($list->pub)) {
3203 $success = $U->simplereq('open-ils.actor',
3204 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3207 } elsif($action eq 'hide') {
3208 if($U->is_true($list->pub)) {
3210 $success = $U->simplereq('open-ils.actor',
3211 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3214 } elsif($action eq 'rename') {
3217 $success = $U->simplereq('open-ils.actor',
3218 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3221 } elsif($action eq 'add_rec') {
3222 foreach my $add_rec (@add_rec) {
3223 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3224 $item->bucket($list_id);
3225 $item->target_biblio_record_entry($add_rec);
3226 $success = $U->simplereq('open-ils.actor',
3227 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3228 last unless $success;
3230 # Redirect back where we came from if we have an anchor parameter:
3231 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3232 $url = $self->ctx->{referer};
3233 $url =~ s/#.*|$/#$anchor/;
3234 } elsif ($cgi->param('where_from')) {
3235 # Or, if we have a "where_from" parameter.
3236 $url = $cgi->param('where_from');
3238 } elsif ($action eq 'del_item') {
3239 foreach (@selected_item) {
3240 $success = $U->simplereq(
3242 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3244 last unless $success;
3246 } elsif ($action eq 'save_notes') {
3247 $success = $self->update_bookbag_item_notes;
3248 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3249 } elsif ($action eq 'make_default') {
3250 $success = $U->simplereq(
3252 'open-ils.actor.patron.settings.update',
3255 { 'opac.default_list' => $list_id }
3257 } elsif ($action eq 'remove_default') {
3258 $success = $U->simplereq(
3260 'open-ils.actor.patron.settings.update',
3263 { 'opac.default_list' => 0 }
3267 return $self->generic_redirect($url) if $success;
3269 $self->ctx->{where_from} = $cgi->param('where_from');
3270 $self->ctx->{bucket_action} = $action;
3271 $self->ctx->{bucket_action_failed} = 1;
3272 return Apache2::Const::OK;
3275 sub update_bookbag_item_notes {
3277 my $e = $self->editor;
3279 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3280 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3282 # We're going to leverage an API call that's already been written to check
3283 # permissions appropriately.
3285 my $a = create OpenSRF::AppSession("open-ils.actor");
3286 my $method = "open-ils.actor.container.item_note.cud";
3288 for my $note_key (@note_keys) {
3291 my $id = ($note_key =~ /(\d+)/)[0];
3294 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3295 my $event = $e->die_event;
3296 $self->apache->log->warn(
3297 "error retrieving cbrebin id $id, got event " .
3301 $self->ctx->{bucket_action_event} = $event;
3305 if (length($self->cgi->param($note_key))) {
3306 $note->ischanged(1);
3307 $note->note($self->cgi->param($note_key));
3309 $note->isdeleted(1);
3312 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3314 if (defined $U->event_code($r)) {
3315 $self->apache->log->warn(
3316 "attempt to modify cbrebin " . $note->id .
3317 " returned event " . $r->{textcode}
3321 $self->ctx->{bucket_action_event} = $r;
3326 for my $item_key (@item_keys) {
3327 my $id = int(($item_key =~ /(\d+)/)[0]);
3328 my $text = $self->cgi->param($item_key);
3331 next unless length $text;
3333 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3338 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3340 if (defined $U->event_code($r)) {
3341 $self->apache->log->warn(
3342 "attempt to create cbrebin for item " . $note->item .
3343 " returned event " . $r->{textcode}
3347 $self->ctx->{bucket_action_event} = $r;
3356 sub load_myopac_bookbag_print {
3359 my $id = int($self->cgi->param("list"));
3361 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3364 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3368 # Get the bookbag object itself, assuming we're allowed to.
3369 if ($self->editor->allowed("VIEW_CONTAINER")) {
3371 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3373 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3377 "owner" => $self->editor->requestor->id,
3381 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3383 $bbag = pop @$bookbags;
3386 # If we have a bookbag we're allowed to look at, issue the A/T event
3387 # to get CSV, passing as a user param that search query we built before.
3389 $self->ctx->{csv} = $U->fire_object_event(
3390 undef, "container.biblio_record_entry_bucket.csv",
3391 $bbag, $self->editor->requestor->home_ou,
3392 undef, {"item_search" => $item_search}
3396 # Create a reasonable filename and set the content disposition to
3397 # provoke browser download dialogs.
3398 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3400 return $self->set_file_download_headers("$filename.csv");
3403 sub load_myopac_circ_history_export {
3405 my $e = $self->editor;
3406 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3408 my $circs = $self->fetch_user_circ_history(1);
3410 $self->ctx->{csv}->{circs} = $circs;
3411 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3415 sub load_myopac_reservations {
3417 my $e = $self->editor;
3418 my $ctx = $self->ctx;
3420 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3421 $e->authtoken, undef
3424 $ctx->{reservations} = $upcoming;
3425 return Apache2::Const::OK;
3429 sub load_password_reset {
3431 my $cgi = $self->cgi;
3432 my $ctx = $self->ctx;
3433 my $barcode = $cgi->param('barcode');
3434 my $username = $cgi->param('username');
3435 my $email = $cgi->param('email');
3436 my $pwd1 = $cgi->param('pwd1');
3437 my $pwd2 = $cgi->param('pwd2');
3438 my $uuid = $ctx->{page_args}->[0];
3442 $logger->info("patron password reset with uuid $uuid");
3444 if ($pwd1 and $pwd2) {
3446 if ($pwd1 eq $pwd2) {
3448 my $response = $U->simplereq(
3450 'open-ils.actor.patron.password_reset.commit',
3453 $logger->info("patron password reset response " . Dumper($response));
3455 if ($U->event_code($response)) { # non-success event
3457 my $code = $response->{textcode};
3459 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3460 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3463 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3464 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3469 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3472 } else { # passwords not equal
3474 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3477 } else { # 2 password values needed
3479 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3482 } elsif ($barcode or $username) {
3484 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3485 push(@params, $email) if $email;
3489 'open-ils.actor.patron.password_reset.request', @params);
3491 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3494 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3495 return Apache2::Const::OK;