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 is_read => defined($aum->read_date) ? 1 : 0,
588 library => $aum->sending_lib->name,
592 $ctx->{patron_messages_limit} = $limit;
593 $ctx->{patron_messages_offset} = $offset;
595 return Apache2::Const::OK;
598 sub _fetch_and_mark_read_single_message {
603 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
604 my $messages = $pcrud->request(
605 'open-ils.pcrud.search.auml.atomic',
606 $self->editor->authtoken,
608 usr => $self->editor->requestor->id,
614 flesh_fields => { auml => ['sending_lib'] },
618 $messages->[0]->read_date('now');
620 'open-ils.pcrud.update.auml',
621 $self->editor->authtoken,
625 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
627 $self->update_dashboard_stats();
632 sub _fetch_user_messages {
638 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
640 my $all_messages = $pcrud->request(
641 'open-ils.pcrud.id_list.auml.atomic',
642 $self->editor->authtoken,
644 usr => $self->editor->requestor->id,
650 my $messages = $pcrud->request(
651 'open-ils.pcrud.search.auml.atomic',
652 $self->editor->authtoken,
654 usr => $self->editor->requestor->id,
659 flesh_fields => { auml => ['sending_lib'] },
660 order_by => { auml => 'create_date DESC' },
665 return scalar(@$all_messages), $messages;
668 sub _handle_message_action {
672 my $cgi = $self->cgi;
674 my @ids = $cgi->param('message_id');
675 return (0, 0) unless @ids;
679 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
681 my $aum = $pcrud->request(
682 'open-ils.pcrud.retrieve.auml',
683 $self->editor->authtoken,
687 if ($action eq 'mark_read') {
688 $aum->read_date('now');
689 } elsif ($action eq 'mark_unread') {
690 $aum->clear_read_date();
691 } elsif ($action eq 'mark_deleted') {
694 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
699 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
701 $failed = scalar(@ids);
703 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
705 return ($changed, $failed);
708 sub _load_lists_and_settings {
710 my $e = $self->editor;
711 my $stat = $self->_load_user_with_prefs;
714 my $setting_map = $self->ctx->{user_setting_map};
715 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
716 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
718 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
719 order_by => {cbreb => 'name'},
720 limit => $self->cgi->param('limit') || 10,
721 offset => $self->cgi->param('offset') || 0
725 # We also want a total count of the user's bookbags.
727 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
729 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
731 my $r = $e->json_query($q);
732 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
733 # Someone has requested that we use the default list's name
734 # rather than "Default List."
737 'select' => {'cbreb' => ['name']},
739 'where' => {'id' => $exclude}
741 $r = $e->json_query($q);
742 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
750 sub update_optin_prefs {
752 my $user_prefs = shift;
753 my $e = $self->editor;
754 my @settings = $self->cgi->param('setting');
757 # apply now-true settings
758 for my $applied (@settings) {
759 # see if setting is already applied to this user
760 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
761 $newsets{$applied} = OpenSRF::Utils::JSON->true;
764 # remove now-false settings
765 for my $pref (grep { $_->{value} } @$user_prefs) {
766 $newsets{$pref->{cust}->name} = undef
767 unless grep { $_ eq $pref->{cust}->name } @settings;
772 'open-ils.actor.patron.settings.update',
773 $e->authtoken, $e->requestor->id, \%newsets);
775 # update the local prefs to match reality
776 for my $pref (@$user_prefs) {
777 $pref->{value} = $newsets{$pref->{cust}->name}
778 if exists $newsets{$pref->{cust}->name};
784 sub _load_user_with_prefs {
786 my $stat = $self->prepare_extended_user_info('settings');
787 return $stat if $stat; # not-OK
789 $self->ctx->{user_setting_map} = {
790 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
791 @{$self->ctx->{user}->settings}
797 sub _get_bookbag_sort_params {
798 my ($self, $param_name) = @_;
800 # The interface that feeds this cgi parameter will provide a single
801 # argument for a QP sort filter, and potentially a modifier after a period.
802 # In practice this means the "sort" parameter will be something like
803 # "titlesort" or "authorsort.descending".
804 my $sorter = $self->cgi->param($param_name) || "";
807 $sorter =~ s/^(.*?)\.(.*)/$1/;
808 $modifier = $2 || undef;
811 return ($sorter, $modifier);
814 sub _prepare_bookbag_container_query {
815 my ($self, $container_id, $sorter, $modifier) = @_;
818 "container(bre,bookbag,%d,%s)%s%s",
819 $container_id, $self->editor->authtoken,
820 ($sorter ? " sort($sorter)" : ""),
821 ($modifier ? "#$modifier" : "")
825 sub _prepare_anonlist_sorting_query {
826 my ($self, $list, $sorter, $modifier) = @_;
829 "record_list(%s)%s%s",
831 ($sorter ? " sort($sorter)" : ""),
832 ($modifier ? "#$modifier" : "")
837 sub load_myopac_prefs_settings {
842 opac.default_search_location
843 opac.default_pickup_location
844 opac.temporary_list_no_warn
847 my $stat = $self->_load_user_with_prefs;
848 return $stat if $stat;
850 # if behind-desk holds are supported and the user
851 # setting which controls the value is opac-visible,
852 # add the setting to the list of settings to manage.
853 # note: this logic may need to be changed later to
854 # check whether behind-the-desk holds are supported
855 # anywhere the patron may select as a pickup lib.
856 my $e = $self->editor;
857 my $bdous = $self->ctx->{get_org_setting}->(
858 $e->requestor->home_ou,
859 'circ.holds.behind_desk_pickup_supported');
863 $e->retrieve_config_usr_setting_type(
864 'circ.holds_behind_desk');
866 if ($U->is_true($setting->opac_visible)) {
867 push(@user_prefs, 'circ.holds_behind_desk');
868 $self->ctx->{behind_desk_supported} = 1;
872 my $use_privacy_waiver = $self->ctx->{get_org_setting}->(
873 $e->requestor->home_ou, 'circ.privacy_waiver');
875 return Apache2::Const::OK
876 unless $self->cgi->request_method eq 'POST';
878 # some setting values from the form don't match the
879 # required value/format for the db, so they have to be
880 # individually translated.
883 my $set_map = $self->ctx->{user_setting_map};
885 foreach my $key (@user_prefs) {
886 my $val = $self->cgi->param($key);
887 $settings{$key}= $val unless $$set_map{$key} eq $val;
890 # Used by the settings update form when warning on history delete.
891 my $clear_circ_history = 0;
892 my $clear_hold_history = 0;
894 # true if we need to show the warning on next page load.
895 my $hist_warning_needed = 0;
896 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
898 my $now = DateTime->now->strftime('%F');
900 qw/history.circ.retention_start history.hold.retention_start/) {
902 my $val = $self->cgi->param($key);
903 if($val and $val eq 'on') {
904 # Set the start time to 'now' unless a start time already exists for the user
905 $settings{$key} = $now unless $$set_map{$key};
909 next unless $$set_map{$key}; # nothing to do
911 $clear_circ_history = 1 if $key =~ /circ/;
912 $clear_hold_history = 1 if $key =~ /hold/;
914 if (!$hist_clear_confirmed) {
915 # when clearing circ history, only warn if history data exists.
917 if ($clear_circ_history) {
919 if ($self->fetch_user_circ_history(0, 1)->[0]) {
920 $hist_warning_needed = 1;
921 next; # no history updates while confirmation pending
926 my $one_hold = $e->json_query({
930 transform => 'action.usr_visible_holds',
935 where => {id => $e->requestor->id},
940 $hist_warning_needed = 1;
941 next; # no history updates while confirmation pending
946 $settings{$key} = undef;
948 if ($key eq 'history.circ.retention_start') {
949 # delete existing circulation history data.
952 'open-ils.actor.history.circ.clear',
953 $self->editor->authtoken);
958 # Warn patrons before clearing circ/hold history
959 if ($hist_warning_needed) {
960 $self->ctx->{clear_circ_history} = $clear_circ_history;
961 $self->ctx->{clear_hold_history} = $clear_hold_history;
962 $self->ctx->{confirm_history_delete} = 1;
965 # Send the modified settings off to be saved
968 'open-ils.actor.patron.settings.update',
969 $self->editor->authtoken, undef, \%settings);
971 $self->ctx->{updated_user_settings} = \%settings;
973 if ($use_privacy_waiver) {
975 my $saved_entries = ();
976 my @waiver_types = qw/place_holds pickup_holds checkout_items view_history/;
978 # initialize our waiver hash with waiver IDs from hidden input
979 # (this ensures that we capture entries with no checked boxes)
980 foreach my $waiver_row_id ($self->cgi->param("waiver_id")) {
981 $waiver{$waiver_row_id} = {};
984 # process our waiver checkboxes into a hash, keyed by waiver ID
985 # (a new entry, if any, has id = 'new')
986 foreach my $waiver_type (@waiver_types) {
987 if ($self->cgi->param("waiver_$waiver_type")) {
988 foreach my $waiver_id ($self->cgi->param("waiver_$waiver_type")) {
989 # ensure this waiver exists in our hash
990 $waiver{$waiver_id} = {} if !$waiver{$waiver_id};
991 $waiver{$waiver_id}->{$waiver_type} = 1;
996 foreach my $k (keys %waiver) {
998 # get name from textbox
999 $w->{name} = $self->cgi->param("waiver_name_$k");
1001 foreach (@waiver_types) {
1002 $w->{$_} = 0 unless ($w->{$_});
1004 push @$saved_entries, $w;
1007 # update patron privacy waiver entries
1010 'open-ils.actor.patron.privacy_waiver.update',
1011 $self->editor->authtoken, undef, $saved_entries);
1013 $self->ctx->{updated_waiver_entries} = $saved_entries;
1016 # re-fetch user prefs
1017 return $self->_load_user_with_prefs || Apache2::Const::OK;
1020 sub load_myopac_prefs_my_lists {
1023 my @user_prefs = qw/
1025 opac.list_items_per_page
1028 my $stat = $self->_load_user_with_prefs;
1029 return $stat if $stat;
1031 return Apache2::Const::OK
1032 unless $self->cgi->request_method eq 'POST';
1035 my $set_map = $self->ctx->{user_setting_map};
1037 foreach my $key (@user_prefs) {
1038 my $val = $self->cgi->param($key);
1039 $settings{$key}= $val unless $$set_map{$key} eq $val;
1042 if (keys %settings) { # we found a different setting value
1043 # Send the modified settings off to be saved
1046 'open-ils.actor.patron.settings.update',
1047 $self->editor->authtoken, undef, \%settings);
1049 # re-fetch user prefs
1050 $self->ctx->{updated_user_settings} = \%settings;
1051 $stat = $self->_load_user_with_prefs;
1054 return $stat || Apache2::Const::OK;
1057 sub fetch_user_holds {
1059 my $hold_ids = shift;
1060 my $ids_only = shift;
1062 my $available = shift;
1066 my $e = $self->editor;
1067 my $all_ids; # to be used below.
1070 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1072 $hold_ids = $circ->request(
1073 'open-ils.circ.holds.id_list.retrieve.authoritative',
1080 $all_ids = $hold_ids;
1081 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
1084 $all_ids = $hold_ids;
1087 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
1090 suppress_notices => 1,
1091 suppress_transits => 1,
1093 suppress_patron_details => 1
1096 # ----------------------------------------------------------------
1097 # Collect holds in batches of $batch_size for faster retrieval
1101 my $mk_req_batch = sub {
1103 my $top_idx = $batch_idx + $batch_size;
1104 while($batch_idx < $top_idx) {
1105 my $hold_id = $hold_ids->[$batch_idx++];
1106 last unless $hold_id;
1107 my $ses = OpenSRF::AppSession->create('open-ils.circ');
1108 my $req = $ses->request(
1109 'open-ils.circ.hold.details.retrieve',
1110 $e->authtoken, $hold_id, $args);
1111 push(@ses, {ses => $ses, req => $req});
1117 my(@collected, @holds, @ses);
1120 @ses = $mk_req_batch->() if $first;
1121 last if $first and not @ses;
1124 while(my $blob = pop(@collected)) {
1127 # in the holds edit UI, we need to know what formats and
1128 # languages the user selected for this hold, plus what
1129 # formats/langs are available on the MR as a whole.
1130 if ($blob->{hold}{hold}->hold_type eq 'M') {
1131 my $hold = $blob->{hold}->{hold};
1133 # for MR, fetch the combined MR unapi blob
1134 (undef, @data) = $self->get_records_and_facets(
1135 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
1137 my $filter_org = $U->org_unit_ancestor_at_depth(
1138 $hold->selection_ou,
1139 $hold->selection_depth);
1141 my $filter_data = $U->simplereq(
1143 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
1144 $hold->target, $filter_org, [$hold->id]
1147 $blob->{metarecord_filters} =
1148 $filter_data->[0]->{metarecord};
1149 $blob->{metarecord_selected_filters} =
1150 $filter_data->[1]->{hold};
1153 (undef, @data) = $self->get_records_and_facets(
1154 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
1158 $blob->{marc_xml} = $data[0]->{marc_xml};
1159 push(@holds, $blob);
1163 for my $req_data (@ses) {
1164 push(@collected, {hold => $req_data->{req}->gather(1)});
1165 $req_data->{ses}->kill_me;
1168 @ses = $mk_req_batch->();
1169 last unless @collected or @ses;
1173 # put the holds back into the original server sort order
1175 for my $id (@$hold_ids) {
1176 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1180 try { # if the service is not running, just let this fail silently
1181 $curbsides = $U->simplereq(
1182 'open-ils.curbside',
1183 'open-ils.curbside.fetch_mine.atomic',
1186 } catch Error with {};
1188 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, curbsides => $curbsides };
1191 sub load_current_curbside_libs {
1193 my $ctx = $self->ctx;
1194 my $e = $self->editor;
1195 my $holds = $e->search_action_hold_request({
1196 usr => $e->requestor->id,
1197 shelf_time => { '!=' => undef },
1198 cancel_time => undef,
1199 fulfillment_time => undef
1203 for my $h (@$holds) {
1204 next if ($h->pickup_lib != $h->current_shelf_lib);
1205 $pickup_libs{$h->pickup_lib} = 1;
1208 my @curbside_pickup_libs;
1209 for my $pul (keys %pickup_libs) {
1210 push(@curbside_pickup_libs, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1213 $ctx->{curbside_pickup_libs} = [
1214 sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } @curbside_pickup_libs
1218 sub handle_hold_update {
1221 my $hold_ids = shift;
1222 my $e = $self->editor;
1223 my $ctx = $self->ctx;
1226 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1227 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1229 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1231 if($action =~ /cancel/) {
1233 for my $hold_id (@hold_ids) {
1234 my $resp = $circ->request(
1235 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1238 } elsif ($action =~ /activate|suspend/) {
1241 for my $hold_id (@hold_ids) {
1242 my $vals = {id => $hold_id};
1244 if($action =~ /activate/) {
1245 $vals->{frozen} = 'f';
1246 $vals->{thaw_date} = undef;
1248 } elsif($action =~ /suspend/) {
1249 $vals->{frozen} = 't';
1250 # $vals->{thaw_date} = TODO;
1252 push(@$vlist, $vals);
1255 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1256 $self->ctx->{hold_suspend_post_capture} = 1 if
1257 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1259 } elsif ($action eq 'edit') {
1262 my $val = {"id" => $_};
1263 $val->{"frozen"} = $self->cgi->param("frozen");
1264 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1265 $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1266 $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1267 $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1268 $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1270 for my $field (qw/expire_time thaw_date/) {
1271 # XXX TODO make this support other date formats, not just
1273 next unless $self->cgi->param($field) =~
1274 m:^(\d{2})/(\d{2})/(\d{4})$:;
1275 $val->{$field} = "$3-$1-$2";
1278 $val->{holdable_formats} = # no-op for non-MR holds
1279 $self->compile_holdable_formats(undef, $_);
1285 'open-ils.circ.hold.update.batch.atomic',
1286 $e->authtoken, undef, \@vals
1287 )->gather(1); # LFW XXX test for failure
1288 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1289 foreach my $param (('loc', 'qtype', 'query')) {
1290 if ($self->cgi->param($param)) {
1291 my @vals = $self->cgi->param($param);
1292 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1295 } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1298 $circ = OpenSRF::AppSession->create('open-ils.curbside');
1300 # see what we're doing with curbside here...
1301 my $cs_action = $self->cgi->param("cs_action");
1302 my $slot_id = $self->cgi->param("cs_slot_id");
1304 # we have an id, let's grab it if we can
1305 my $slot = $e->retrieve_action_curbside($slot_id);
1306 $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1308 my $org = $self->cgi->param("cs_org");
1309 my $date = $self->cgi->param("cs_date");
1310 my $time = $self->cgi->param("cs_time");
1311 my $notes = $self->cgi->param("cs_notes");
1314 $org ||= $slot->org;
1315 $notes ||= $slot->notes;
1317 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1318 $date ||= $dt->strftime('%F');
1319 $time ||= $dt->strftime('%T');
1323 $ctx->{cs_org} = $org;
1324 $ctx->{cs_date} = $date;
1325 $ctx->{cs_time} = $time;
1326 $ctx->{cs_notes} = $notes;
1327 $ctx->{cs_slot_id} = $slot->id if ($slot);
1328 $ctx->{cs_slot} = $slot;
1330 if ($cs_action eq 'reset') {
1331 $ctx->{cs_org} = $org = undef;
1332 $ctx->{cs_date} = $date = undef;
1333 $ctx->{cs_time} = $time = undef;
1334 $ctx->{cs_notes} = $notes = undef;
1335 $ctx->{cs_slot_id} = $slot_id = undef;
1336 $ctx->{cs_slot} = $slot = undef;
1337 } elsif ($cs_action eq 'save' && $org && $date && $time) {
1338 my $mode = $slot ? 'update' : 'create';
1339 $slot = $circ->request(
1340 "open-ils.curbside.${mode}_appointment",
1341 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1344 if (defined $U->event_code($slot)) {
1345 $self->apache->log->warn(
1346 "error attempting to $mode a curbside appointment for patron ".
1347 $e->requestor->id . ", got event " . $slot->{textcode}
1349 $ctx->{curbside_action_event} = $slot;
1350 $ctx->{cs_slot} = undef;
1352 $ctx->{cs_slot} = $slot;
1354 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1355 } elsif ($cs_action eq 'cancel' && $slot) {
1356 my $curbsides = $U->simplereq(
1357 'open-ils.curbside',
1358 'open-ils.curbside.delete_appointment',
1359 $e->authtoken, $slot->id
1361 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1362 } elsif ($cs_action eq 'arrive' && $slot) {
1363 my $curbsides = $U->simplereq(
1364 'open-ils.curbside',
1365 'open-ils.curbside.mark_arrived',
1366 $e->authtoken, $slot->id
1368 } elsif ($cs_action eq 'deliver' && $slot) {
1369 my $curbsides = $U->simplereq(
1370 'open-ils.curbside',
1371 'open-ils.curbside.mark_delivered',
1372 $e->authtoken, $slot->id
1376 if ($date and $org and !$ctx->{cs_times}{$org}{$date}) {
1377 $ctx->{cs_times}{$org}{$date} = $circ->request(
1378 'open-ils.curbside.times_for_date.atomic',
1379 $e->authtoken, $date, $org
1385 return defined($url) ? $self->generic_redirect($url) : undef;
1388 sub load_myopac_holds {
1390 my $e = $self->editor;
1391 my $ctx = $self->ctx;
1393 my $limit = $self->cgi->param('limit') || 15;
1394 my $offset = $self->cgi->param('offset') || 0;
1395 my $action = $self->cgi->param('action') || '';
1396 my $hold_id = $self->cgi->param('hid');
1397 my $available = int($self->cgi->param('available') || 0);
1399 my $hold_handle_result;
1400 $hold_handle_result = $self->handle_hold_update($action) if $action;
1403 if ($self->cgi->param('sort') ne "") {
1404 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1407 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1410 if($holds_object->{holds}) {
1411 $ctx->{holds} = $holds_object->{holds};
1412 $ctx->{curbside_appointments} = {};
1414 $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1416 for my $cs (@{$holds_object->{curbsides}}) {
1418 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1419 $ctx->{cs_times}{$cs->org}{$dt} = $U->simplereq(
1420 'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1421 $e->authtoken, $dt, $cs->org
1424 $ctx->{curbside_appointments}{$cs->org} = $cs;
1427 $ctx->{holds_ids} = $holds_object->{all_ids};
1428 $ctx->{holds_limit} = $limit;
1429 $ctx->{holds_offset} = $offset;
1431 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1434 sub load_myopac_hold_subscriptions {
1436 my $e = $self->editor;
1437 my $ctx = $self->ctx;
1439 my $sub_remove = $self->cgi->param('remove');
1441 if ($sub_remove and $ctx->{user}->id) {
1442 my $sub_entries = $self->editor->search_container_user_bucket_item(
1443 { bucket => $sub_remove, target_user => $ctx->{user}->id }
1446 $self->editor->xact_begin;
1447 $self->editor->delete_container_user_bucket_item($_) for @$sub_entries;
1448 $self->editor->xact_commit;
1450 return $self->generic_redirect(
1451 $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/hold_subscriptions'
1455 return Apache2::Const::OK;
1460 sub load_place_hold {
1462 my $ctx = $self->ctx;
1463 my $gos = $ctx->{get_org_setting};
1464 my $e = $self->editor;
1465 my $cgi = $self->cgi;
1467 $self->ctx->{page} = 'place_hold';
1468 my @targets = uniq $cgi->param('hold_target');
1469 my @parts = $cgi->param('part');
1471 $ctx->{hold_subscription} = $cgi->param('hold_subscription');
1472 $ctx->{hold_type} = $cgi->param('hold_type');
1473 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1474 $ctx->{email_notify} = $cgi->param('email_notify');
1475 if ($cgi->param('phone_notify_checkbox')) {
1476 $ctx->{phone_notify} = $cgi->param('phone_notify');
1478 if ($cgi->param('sms_notify_checkbox')) {
1479 $ctx->{sms_notify} = $cgi->param('sms_notify');
1480 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1483 return $self->generic_redirect unless @targets;
1485 # Check for multiple hold placement via the num_copies widget.
1486 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1487 if ($num_copies > 1) {
1488 # Only if we have 1 hold target and no parts.
1489 if (scalar(@targets) == 1 && !$parts[0]) {
1490 # Also, only for M and T holds.
1491 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1492 # Add the extra holds to @targets. NOTE: We start with
1493 # 1 and go to < $num_copies to account for the
1495 for (my $i = 1; $i < $num_copies; $i++) {
1496 push(@targets, $targets[0]);
1502 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1504 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1509 au => ['settings', 'card']
1512 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1513 my $user_setting_map = {
1514 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1516 $ctx->{staff_recipient}->settings
1519 $ctx->{user_setting_map} = $user_setting_map;
1521 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1522 if ($default_notify =~ /email/) {
1523 $ctx->{default_email_notify} = 'checked';
1525 $ctx->{default_email_notify} = '';
1527 if ($default_notify =~ /phone/) {
1528 $ctx->{default_phone_notify} = 'checked';
1530 $ctx->{default_phone_notify} = '';
1532 if ($default_notify =~ /sms/) {
1533 $ctx->{default_sms_notify} = 'checked';
1535 $ctx->{default_sms_notify} = '';
1537 if ($cgi->param('hold_suspend')) {
1539 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1540 # We should use a date input type on the forms once it is supported by Firefox.
1541 # I didn't do that now because it is not available in a general release.
1542 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1544 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1545 $ctx->{thaw_date} = $dt->ymd;
1548 $logger->warn("ignoring invalid thaw_date when placing hold request");
1554 # If we have a default pickup location, grab it
1555 if ($$user_setting_map{'opac.default_pickup_location'}) {
1556 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1559 my $request_lib = $e->requestor->ws_ou;
1561 $ctx->{hold_data} = \@hold_data;
1563 $data_filler = sub {
1565 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1566 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1567 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1568 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1569 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1570 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1574 my $type_dispatch = {
1576 # target metarecords
1577 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1579 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1583 for my $id (@targets) {
1584 my ($mr) = grep {$_->id eq $id} @$mrecs;
1586 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1587 my $filter_data = $U->simplereq(
1589 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1591 my $holdable_formats =
1592 $self->compile_holdable_formats($mr->id);
1594 push(@hold_data, $data_filler->({
1596 record => $mr->master_record,
1597 holdable_formats => $holdable_formats,
1598 metarecord_filters => $filter_data->{metarecord}
1603 my $recs = $e->batch_retrieve_biblio_record_entry(
1604 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1608 for my $id (@targets) { # force back into the correct order
1609 my ($rec) = grep {$_->id eq $id} @$recs;
1611 # NOTE: if tpac ever supports locked-down pickup libs,
1612 # we'll need to pass a pickup_lib param along with the
1613 # record to filter the set of monographic parts.
1614 my $parts = $U->simplereq(
1616 'open-ils.search.biblio.record_hold_parts',
1617 {record => $rec->id}
1620 # T holds on records that have parts are OK, but if the record has
1621 # no non-part copies, the hold will ultimately fail. When that
1622 # happens, require the user to select a part.
1623 my $part_required = 0;
1625 my $np_copies = $e->json_query({
1626 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1627 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1629 '+acp' => {deleted => 'f'},
1630 '+acn' => {deleted => 'f', record => $rec->id},
1631 '+acpm' => {id => undef}
1634 $part_required = 1 if $np_copies->[0]->{count} == 0;
1637 push(@hold_data, $data_filler->({
1641 part_required => $part_required
1646 my $vols = $e->batch_retrieve_asset_call_number([
1649 "flesh_fields" => {"acn" => ["record"]}
1651 ], {substream => 1});
1653 for my $id (@targets) {
1654 my ($vol) = grep {$_->id eq $id} @$vols;
1655 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1659 my $copies = $e->batch_retrieve_asset_copy([
1663 "acn" => ["record"],
1664 "acp" => ["call_number"]
1667 ], {substream => 1});
1669 for my $id (@targets) {
1670 my ($copy) = grep {$_->id eq $id} @$copies;
1671 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1675 my $isses = $e->batch_retrieve_serial_issuance([
1679 "siss" => ["subscription"], "ssub" => ["record_entry"]
1682 ], {substream => 1});
1684 for my $id (@targets) {
1685 my ($iss) = grep {$_->id eq $id} @$isses;
1686 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1691 }->{$ctx->{hold_type}}->();
1693 # caller sent bad target IDs or the wrong hold type
1694 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1696 # generate the MARC xml for each record
1697 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1699 my $pickup_lib = $cgi->param('pickup_lib');
1700 # no pickup lib means no holds placement, except for subscriptions
1701 return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1703 $ctx->{hold_attempt_made} = 1;
1705 # Give the original CGI params back to the user in case they
1706 # want to try to override something.
1707 $ctx->{orig_params} = $cgi->Vars;
1708 delete $ctx->{orig_params}{submit};
1709 delete $ctx->{orig_params}{hold_target};
1710 delete $ctx->{orig_params}{part};
1712 my $usr = $e->requestor->id;
1714 if ($ctx->{is_staff}) {
1715 $logger->info("Staff initiated hold");
1716 if (!$cgi->param("hold_usr_is_requestor")) {
1717 # find the real hold target
1719 $usr = $U->simplereq(
1721 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1722 $e->authtoken, $cgi->param("hold_usr"));
1724 if (defined $U->event_code($usr)) {
1725 $ctx->{hold_failed} = 1;
1726 $ctx->{hold_failed_event} = $usr;
1730 if ($ctx->{hold_subscription}) {
1731 # this is a batch event, hold "user" is a bucket id
1732 $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1733 $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1737 # target_id is the true target_id for holds placement.
1738 # needed for attempt_hold_placement()
1739 # With the exception of P-type holds, target_id == target->id.
1740 $_->{target_id} = $_->{target}->id for @hold_data;
1742 if ($ctx->{hold_type} eq 'T') {
1744 # Much like quantum wave-particles, P-type holds pop into
1745 # and out of existence at the user's whim. For our purposes,
1746 # we treat such holds as T(itle) holds with a selected_part
1747 # designation. When the time comes to pass the hold information
1748 # off for holds possibility testing and placement, make it look
1749 # like a real P-type hold.
1750 my (@p_holds, @t_holds);
1752 # Now that we have the num_copies field for mutliple title and
1753 # metarecord hold placement, the number of holds and parts
1754 # arrays can get out of sync. We only want to parse out parts
1755 # if the numbers are equal.
1756 if ($#hold_data == $#parts) {
1757 for my $idx (0..$#parts) {
1758 my $hdata = $hold_data[$idx];
1759 if (my $part = $parts[$idx]) {
1760 $hdata->{target_id} = $part;
1761 $hdata->{selected_part} = $part;
1762 push(@p_holds, $hdata);
1764 push(@t_holds, $hdata);
1768 @t_holds = @hold_data;
1771 $self->apache->log->warn("$#parts : @t_holds");
1773 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1774 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1777 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1780 # NOTE: we are leaving the staff-placed patron barcode cookie
1781 # in place. Otherwise, it's not possible to place more than
1782 # one hold for the patron within a staff/patron session. This
1783 # does leave the barcode to linger longer than is ideal, but
1784 # normal staff work flow will cause the cookie to be replaced
1785 # with each new patron anyway.
1786 # TODO: See about getting the staff client to clear the cookie
1788 # return to the place_hold page so the results of the hold
1789 # placement attempt can be reported to the user
1790 return Apache2::Const::OK;
1793 sub attempt_hold_placement {
1794 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1795 my $cgi = $self->cgi;
1796 my $ctx = $self->ctx;
1797 my $e = $self->editor;
1799 my $user_container = undef;
1800 if (ref($usr)) { # $usr is actually a container for a subscription...
1801 $user_container = $usr->id;
1802 return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1805 # First see if we should warn/block for any holds that
1806 # might have locally available items for non-subscriptions.
1807 if (!$user_container) {
1808 for my $hdata (@hold_data) {
1809 my ($local_block, $local_alert) = $self->local_avail_concern(
1810 $hdata->{target_id}, $hold_type, $pickup_lib);
1813 $hdata->{hold_failed} = 1;
1814 $hdata->{hold_local_block} = 1;
1815 } elsif ($local_alert) {
1816 $hdata->{hold_failed} = 1;
1817 $hdata->{hold_local_alert} = 1;
1822 my $method = $user_container
1823 ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1824 : 'open-ils.circ.holds.test_and_create.batch';
1826 if ($cgi->param('override')) {
1827 $method .= '.override';
1829 } elsif (!$ctx->{is_staff}) {
1831 $method .= '.override' if $self->ctx->{get_org_setting}->(
1832 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1835 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1838 if(@create_targets) {
1840 # holdable formats may be different for each MR hold.
1841 # map each set to the ID of the target.
1842 my $holdable_formats = {};
1843 if ($hold_type eq 'M') {
1844 $holdable_formats->{$_->{target_id}} =
1845 $_->{holdable_formats} for @hold_data;
1848 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1850 my @create_params = ();
1852 if ($user_container) {
1855 hold_type => $hold_type,
1856 holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1865 pickup_lib => $pickup_lib,
1866 hold_type => $hold_type,
1867 holdable_formats_map => $holdable_formats,
1873 my $breq = $bses->request($method, $e->authtoken, @create_params);
1875 while (my $resp = $breq->recv) {
1877 $resp = $resp->content;
1878 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1880 if ($U->event_code($resp)) {
1881 $ctx->{general_hold_error} = $resp;
1885 # subscription batch create sends an initial response to assist with client-side counting
1888 defined($$resp{count}) and $$resp{count} == 0
1889 and defined($$resp{total}) and $$resp{total} > 0
1892 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1893 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1894 my $result = $resp->{result};
1896 if ($U->event_code($result)) {
1897 # e.g. permission denied
1898 $hdata->{hold_failed} = 1;
1899 $hdata->{hold_failed_event} = $result;
1903 if(not ref $result and $result > 0) {
1904 # successul hold returns the hold ID
1905 $hdata->{hold_success} = $result;
1908 # hold-specific failure event
1909 $hdata->{hold_failed} = 1;
1911 if (ref $result eq 'HASH') {
1912 $hdata->{hold_failed_event} = $result->{last_event};
1914 if ($result->{age_protected_copy}) {
1915 my %temp = %{$hdata->{hold_failed_event}};
1916 my $theTextcode = $temp{"textcode"};
1917 $theTextcode.=".override";
1918 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1919 $hdata->{age_protect} = 1;
1921 $hdata->{could_override} = $result->{place_unfillable} ||
1922 $self->test_could_override($hdata->{hold_failed_event});
1924 } elsif (ref $result eq 'ARRAY') {
1925 $hdata->{hold_failed_event} = $result->[0];
1927 if ($result->[3]) { # age_protect_only
1928 my %temp = %{$hdata->{hold_failed_event}};
1929 my $theTextcode = $temp{"textcode"};
1930 $theTextcode.=".override";
1931 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1932 $hdata->{age_protect} = 1;
1934 $hdata->{could_override} = $result->[4] || # place_unfillable
1935 $self->test_could_override($hdata->{hold_failed_event});
1945 if ($self->cgi->param('clear_cart')) {
1946 $self->clear_anon_cache;
1950 # pull the selected formats and languages for metarecord holds
1951 # from the CGI params and map them into the JSON holdable
1952 # formats...er, format.
1953 # if no metarecord is provided, we'll pull it from the target
1954 # of the provided hold.
1955 sub compile_holdable_formats {
1956 my ($self, $mr_id, $hold_id) = @_;
1957 my $e = $self->editor;
1958 my $cgi = $self->cgi;
1960 # exit early if not needed
1962 grep /metarecord_formats_|metarecord_langs_/,
1965 # CGI params are based on the MR id, since during hold placement
1966 # we have no old ID. During hold edit, map the hold ID back to
1967 # the metarecod target.
1969 $e->retrieve_action_hold_request($hold_id)->target
1972 my $format_attr = $self->ctx->{get_cgf}->(
1973 'opac.metarecord.holds.format_attr');
1975 if (!$format_attr) {
1976 $logger->error("Missing config.global_flag: ".
1977 "opac.metarecord.holds.format_attr!");
1981 $format_attr = $format_attr->value;
1983 # during hold placement or edit submission, the user selects
1984 # which of the available formats/langs are acceptable.
1985 # Capture those here as the holdable_formats for the MR hold.
1986 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1987 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1989 # map the selected attrs into the JSON holdable_formats structure
1991 if (@selected_formats) {
1993 map { {_attr => $format_attr, _val => $_} }
1997 if (@selected_langs) {
1999 map { {_attr => 'item_lang', _val => $_} }
2004 return OpenSRF::Utils::JSON->perl2JSON($blob);
2007 sub fetch_user_circs {
2009 my $flesh = shift; # flesh bib data, etc.
2010 my $circ_ids = shift;
2014 my $e = $self->editor;
2019 @circ_ids = @$circ_ids;
2024 select => {circ => ['id']},
2028 usr => $e->requestor->id,
2029 checkin_time => undef,
2031 {stop_fines => undef},
2032 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2036 order_by => {circ => ['due_date']}
2039 $query->{limit} = $limit if $limit;
2040 $query->{offset} = $offset if $offset;
2042 my $ids = $e->json_query($query);
2043 @circ_ids = map {$_->{id}} @$ids;
2046 return [] unless @circ_ids;
2051 circ => ['target_copy'],
2052 acp => ['call_number'],
2053 acn => ['record','owning_lib']
2058 my $circs = $e->search_action_circulation(
2059 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2062 for my $circ (@$circs) {
2065 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2066 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2067 undef # pre-cat copy, use the dummy title/author instead
2072 # make sure the final list is in the correct order
2074 for my $id (@circ_ids) {
2077 (grep { $_->{circ}->id == $id } @circs)
2081 return \@sorted_circs;
2085 sub handle_circ_renew {
2088 my $ctx = $self->ctx;
2090 my @renew_ids = $self->cgi->param('circ');
2092 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2094 # TODO: fire off renewal calls in batches to speed things up
2096 for my $circ (@$circs) {
2098 my $evt = $U->simplereq(
2100 'open-ils.circ.renew',
2101 $self->editor->authtoken,
2103 patron_id => $self->editor->requestor->id,
2104 copy_id => $circ->{circ}->target_copy,
2109 # TODO return these, then insert them into the circ data
2110 # blob that is shoved into the template for each circ
2111 # so the template won't have to match them
2112 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2118 sub load_myopac_circs {
2120 my $e = $self->editor;
2121 my $ctx = $self->ctx;
2124 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2125 my $offset = $self->cgi->param('offset') || 0;
2126 my $action = $self->cgi->param('action') || '';
2128 # perform the renewal first if necessary
2129 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2131 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2133 my $success_renewals = 0;
2134 my $failed_renewals = 0;
2135 for my $data (@{$ctx->{circs}}) {
2136 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2139 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2141 # extract the fail_part, if present, from the event payload;
2142 # since # the payload is an acp object in some cases,
2143 # blindly looking for a # 'fail_part' key in the template can
2145 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2146 $evt->{payload}->{fail_part} :
2149 $data->{renewal_response} = $evt;
2150 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2151 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2155 $ctx->{success_renewals} = $success_renewals;
2156 $ctx->{failed_renewals} = $failed_renewals;
2158 return Apache2::Const::OK;
2161 sub load_myopac_circ_history {
2163 my $e = $self->editor;
2164 my $ctx = $self->ctx;
2165 my $limit = $self->cgi->param('limit') || 15;
2166 my $offset = $self->cgi->param('offset') || 0;
2167 my $action = $self->cgi->param('action') || '';
2169 my $circ_handle_result;
2170 $circ_handle_result = $self->handle_circ_update($action) if $action;
2172 $ctx->{circ_history_limit} = $limit;
2173 $ctx->{circ_history_offset} = $offset;
2175 # Defer limitation to circ_history.tt2 when sorting
2176 if ($self->cgi->param('sort')) {
2181 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2182 return Apache2::Const::OK;
2185 # if 'flesh' is set, copy data etc. is loaded and the return value is
2186 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2188 sub fetch_user_circ_history {
2189 my ($self, $flesh, $limit, $offset) = @_;
2190 my $e = $self->editor;
2193 $limits{offset} = $offset if defined $offset;
2194 $limits{limit} = $limit if defined $limit;
2199 auch => ['target_copy','source_circ'],
2200 acp => ['call_number'],
2206 my $circs = $e->search_action_user_circ_history(
2208 {usr => $e->requestor->id},
2209 { # order newest to oldest by default
2210 order_by => {auch => 'xact_start DESC'},
2211 $flesh ? %flesh_ops : (),
2219 return $circs unless $flesh;
2223 my %unapi_cache = ();
2224 for my $circ (@$circs) {
2225 if ($circ->target_copy->call_number->id == -1) {
2228 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2232 my $bre_id = $circ->target_copy->call_number->record->id;
2234 if (exists $unapi_cache{$bre_id}) {
2235 $unapi = $unapi_cache{$bre_id};
2237 my $result = $e->json_query({
2239 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2243 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2254 marc_xml => undef # failed, but try to go on
2263 sub handle_circ_update {
2266 my $circ_ids = shift;
2268 $circ_ids //= [$self->cgi->param('circ_id')];
2270 if ($action =~ /delete/) {
2272 circ_ids => $circ_ids,
2277 'open-ils.actor.history.circ.clear',
2278 $self->editor->authtoken,
2286 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2287 sub load_myopac_hold_history {
2289 my $e = $self->editor;
2290 my $ctx = $self->ctx;
2291 my $limit = $self->cgi->param('limit') || 15;
2292 my $offset = $self->cgi->param('offset') || 0;
2293 $ctx->{hold_history_limit} = $limit;
2294 $ctx->{hold_history_offset} = $offset;
2296 my $hold_ids = $e->json_query({
2300 transform => 'action.usr_visible_holds',
2301 result_field => 'id'
2305 where => {id => $e->requestor->id}
2308 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2309 if($holds_object->{holds}) {
2310 $ctx->{holds} = $holds_object->{holds};
2312 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2314 return Apache2::Const::OK;
2317 sub load_myopac_payment_form {
2320 my $e = $self->editor;
2322 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2324 if ( ! $self->cgi->param('last_chance') # only do this once
2325 && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')
2326 && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2327 my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2328 my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2329 my $stripe = Business::Stripe->new(-api_key => $skey);
2330 my $intent = $stripe->api('post', 'payment_intents',
2331 amount => $self->ctx->{fines}->{balance_owed} * 100,
2332 currency => $currency || 'usd'
2334 if ($stripe->success) {
2335 $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2337 $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2338 $self->ctx->{cc_configuration_error} = 1;
2342 if ($r) { return $r; }
2343 $r = $self->prepare_extended_user_info and return $r;
2345 return Apache2::Const::OK;
2348 # TODO: add other filter options as params/configs/etc.
2349 sub load_myopac_payments {
2351 my $limit = $self->cgi->param('limit') || 20;
2352 my $offset = $self->cgi->param('offset') || 0;
2353 my $e = $self->editor;
2355 $self->ctx->{payment_history_limit} = $limit;
2356 $self->ctx->{payment_history_offset} = $offset;
2359 $args->{limit} = $limit if $limit;
2360 $args->{offset} = $offset if $offset;
2362 if (my $max_age = $self->ctx->{get_org_setting}->(
2363 $e->requestor->home_ou, "opac.payment_history_age_limit"
2365 my $min_ts = DateTime->now(
2366 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2367 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2369 $logger->info("XXX min_ts: $min_ts");
2370 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2373 $self->ctx->{payments} = $U->simplereq(
2375 'open-ils.actor.user.payments.retrieve.atomic',
2376 $e->authtoken, $e->requestor->id, $args);
2378 return Apache2::Const::OK;
2381 # 1. caches the form parameters
2382 # 2. loads the credit card payment "Processing..." page
2383 sub load_myopac_pay_init {
2385 my $cache = OpenSRF::Utils::Cache->new('global');
2387 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2389 if (!@payment_xacts) {
2390 # for consistency with load_myopac_payment_form() and
2391 # to preserve backwards compatibility, if no xacts are
2392 # selected, assume all (applicable) transactions are wanted.
2393 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2394 return $stat if $stat;
2396 map { $_->{xact}->id } (
2397 @{$self->ctx->{fines}->{circulation}},
2398 @{$self->ctx->{fines}->{grocery}}
2402 return $self->generic_redirect unless @payment_xacts;
2404 my $cc_args = {"where_process" => 1};
2406 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2407 number cvv2 expire_year expire_month billing_first
2408 billing_last billing_address billing_city billing_state
2409 billing_zip stripe_payment_intent stripe_client_secret
2413 cc_args => $cc_args,
2414 user => $self->ctx->{user}->id,
2415 xacts => \@payment_xacts
2418 # generate a temporary cache token and cache the form data
2419 my $token = md5_hex($$ . time() . rand());
2420 $cache->put_cache($token, $cache_args, 30);
2422 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2424 # after we render the processing page, we quickly redirect to submit
2425 # the actual payment. The refresh url contains the payment token.
2426 # It also contains the list of xact IDs, which allows us to clear the
2427 # cache at the earliest possible time while leaving a trace of which
2428 # transactions we were processing, so the UI can bring the user back
2429 # to the payment form w/ the same xacts if the payment fails.
2431 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2432 $refresh .= ";xact=$_" for @payment_xacts;
2433 $self->ctx->{refresh} = $refresh;
2435 return Apache2::Const::OK;
2438 # retrieve the cached CC payment info and send off for processing
2439 sub load_myopac_pay {
2441 my $token = $self->ctx->{page_args}->[0];
2442 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2444 my $cache = OpenSRF::Utils::Cache->new('global');
2445 my $cache_args = $cache->get_cache($token);
2446 $cache->delete_cache($token);
2448 # this page is loaded immediately after the token is created.
2449 # if the cached data is not there, it's because of an invalid
2450 # token (or cache failure) and not because of a timeout.
2451 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2453 my @payment_xacts = @{$cache_args->{xacts}};
2454 my $cc_args = $cache_args->{cc_args};
2456 # as an added security check, verify the user submitting
2457 # the form is the same as the user whose data was cached
2458 return Apache2::Const::HTTP_BAD_REQUEST unless
2459 $cache_args->{user} == $self->ctx->{user}->id;
2461 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2464 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2466 # balance_owed is computed specifically from the fines we're paying
2467 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2468 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2469 return Apache2::Const::HTTP_BAD_REQUEST;
2473 "cc_args" => $cc_args,
2474 "userid" => $self->ctx->{user}->id,
2475 "payment_type" => "credit_card_payment",
2476 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2479 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2480 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2483 $self->ctx->{"payment_response"} = $resp;
2485 unless ($resp->{"textcode"}) {
2486 $self->ctx->{printable_receipt} = $U->simplereq(
2487 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2488 $self->editor->authtoken, $resp->{payments}
2492 return Apache2::Const::OK;
2495 sub load_myopac_receipt_print {
2498 $self->ctx->{printable_receipt} = $U->simplereq(
2499 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2500 $self->editor->authtoken, [$self->cgi->param("payment")]
2503 return Apache2::Const::OK;
2506 sub load_myopac_receipt_email {
2509 # The following ML method doesn't actually check whether the user in
2510 # question has an email address, so we do.
2511 if ($self->ctx->{user}->email) {
2512 $self->ctx->{email_receipt_result} = $U->simplereq(
2513 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2514 $self->editor->authtoken, [$self->cgi->param("payment")]
2517 $self->ctx->{email_receipt_result} =
2518 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2521 return Apache2::Const::OK;
2525 my ($self, $limit, $offset, $id_list) = @_;
2527 # XXX TODO: check for failure after various network calls
2529 # It may be unclear, but this result structure lumps circulation and
2530 # reservation fines together, and keeps grocery fines separate.
2531 $self->ctx->{"fines"} = {
2532 "circulation" => [],
2539 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2541 # TODO: This should really be a ML call, but the existing calls
2542 # return an excessive amount of data and don't offer streaming
2544 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2546 my $req = $cstore->request(
2547 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2549 usr => $self->editor->requestor->id,
2550 balance_owed => {'!=' => 0},
2551 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2556 mobts => [qw/grocery circulation reservation/],
2557 bresv => ['target_resource_type'],
2561 circ => ['target_copy'],
2562 acp => ['call_number'],
2565 order_by => { mobts => 'xact_start' },
2570 # Collect $$ amounts from each transaction for summing below.
2571 my (@paid_amounts, @owed_amounts, @balance_amounts);
2573 while(my $resp = $req->recv) {
2574 my $mobts = $resp->content;
2575 my $circ = $mobts->circulation;
2578 if($mobts->grocery) {
2579 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2580 $last_billing = pop(@billings);
2583 push(@paid_amounts, $mobts->total_paid);
2584 push(@owed_amounts, $mobts->total_owed);
2585 push(@balance_amounts, $mobts->balance_owed);
2587 my $marc_xml = undef;
2588 if ($mobts->xact_type eq 'reservation' and
2589 $mobts->reservation->target_resource_type->record) {
2590 $marc_xml = XML::LibXML->new->parse_string(
2591 $mobts->reservation->target_resource_type->record->marc
2593 } elsif ($mobts->xact_type eq 'circulation' and
2594 $circ->target_copy->call_number->id != -1) {
2595 $marc_xml = XML::LibXML->new->parse_string(
2596 $circ->target_copy->call_number->record->marc
2601 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2604 last_grocery_billing => $last_billing,
2605 marc_xml => $marc_xml
2612 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2613 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2614 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2619 sub prepare_fines_for_payment {
2620 # This assumes $self->prepare_fines has already been run
2624 if ($self->ctx->{fines}) {
2625 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2626 @{$self->ctx->{fines}->{circulation}},
2627 @{$self->ctx->{fines}->{grocery}}
2634 sub load_myopac_main {
2636 my $limit = $self->cgi->param('limit') || 0;
2637 my $offset = $self->cgi->param('offset') || 0;
2638 $self->ctx->{search_ou} = $self->_get_search_lib();
2639 $self->ctx->{user}->notes(
2640 $self->editor->search_actor_usr_note({
2641 usr => $self->ctx->{user}->id,
2645 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2648 sub load_myopac_update_email {
2650 my $e = $self->editor;
2651 my $ctx = $self->ctx;
2652 my $email = $self->cgi->param('email') || '';
2653 my $current_pw = $self->cgi->param('current_pw') || '';
2655 # needed for most up-to-date email address
2656 if (my $r = $self->prepare_extended_user_info) { return $r };
2658 return Apache2::Const::OK
2659 unless $self->cgi->request_method eq 'POST';
2661 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2662 $ctx->{invalid_email} = $email;
2663 return Apache2::Const::OK;
2666 my $stat = $U->simplereq(
2668 'open-ils.actor.user.email.update',
2669 $e->authtoken, $email, $current_pw);
2671 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2672 $ctx->{password_incorrect} = 1;
2673 return Apache2::Const::OK;
2676 unless ($self->cgi->param("redirect_to")) {
2677 my $url = $self->apache->unparsed_uri;
2678 $url =~ s/update_email/prefs/;
2680 return $self->generic_redirect($url);
2683 return $self->generic_redirect;
2686 sub load_myopac_update_username {
2688 my $e = $self->editor;
2689 my $ctx = $self->ctx;
2690 my $username = $self->cgi->param('username') || '';
2691 my $current_pw = $self->cgi->param('current_pw') || '';
2693 $self->prepare_extended_user_info;
2695 my $allow_change = 1;
2697 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2698 if(defined($lock_usernames) and $lock_usernames == 1) {
2699 # Policy says no username changes
2702 # We want this further down.
2703 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2704 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2705 if(!$username_unlimit) {
2707 # Default is "starts with a number"
2708 $regex_check = '^\d+';
2710 # You already have a username?
2711 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2716 if(!$allow_change) {
2717 my $url = $self->apache->unparsed_uri;
2718 $url =~ s/update_username/prefs/;
2720 return $self->generic_redirect($url);
2723 return Apache2::Const::OK
2724 unless $self->cgi->request_method eq 'POST';
2726 unless($username and $username !~ /\s/) { # any other username restrictions?
2727 $ctx->{invalid_username} = $username;
2728 return Apache2::Const::OK;
2731 # New username can't look like a barcode if we have a barcode regex
2732 if($regex_check and $username =~ /$regex_check/) {
2733 $ctx->{invalid_username} = $username;
2734 return Apache2::Const::OK;
2737 # New username has to look like a username if we have a username regex
2738 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2739 if($regex_check and $username !~ /$regex_check/) {
2740 $ctx->{invalid_username} = $username;
2741 return Apache2::Const::OK;
2744 if($username ne $e->requestor->usrname) {
2746 my $evt = $U->simplereq(
2748 'open-ils.actor.user.username.update',
2749 $e->authtoken, $username, $current_pw);
2751 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2752 $ctx->{password_incorrect} = 1;
2753 return Apache2::Const::OK;
2756 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2757 $ctx->{username_exists} = $username;
2758 return Apache2::Const::OK;
2762 my $url = $self->apache->unparsed_uri;
2763 $url =~ s/update_username/prefs/;
2765 return $self->generic_redirect($url);
2768 sub load_myopac_update_password {
2770 my $e = $self->editor;
2771 my $ctx = $self->ctx;
2773 return Apache2::Const::OK
2774 unless $self->cgi->request_method eq 'POST';
2776 my $current_pw = $self->cgi->param('current_pw') || '';
2777 my $new_pw = $self->cgi->param('new_pw') || '';
2778 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2780 unless($new_pw eq $new_pw2) {
2781 $ctx->{password_nomatch} = 1;
2782 return Apache2::Const::OK;
2785 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2788 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2789 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2792 if($pw_regex and $new_pw !~ /$pw_regex/) {
2793 $ctx->{password_invalid} = 1;
2794 return Apache2::Const::OK;
2797 my $evt = $U->simplereq(
2799 'open-ils.actor.user.password.update',
2800 $e->authtoken, $new_pw, $current_pw);
2803 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2804 $ctx->{password_incorrect} = 1;
2805 return Apache2::Const::OK;
2808 my $url = $self->apache->unparsed_uri;
2809 $url =~ s/update_password/prefs/;
2811 return $self->generic_redirect($url);
2814 sub _update_bookbag_metadata {
2815 my ($self, $bookbag) = @_;
2817 $bookbag->name($self->cgi->param("name"));
2818 $bookbag->description($self->cgi->param("description"));
2820 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2824 sub _get_lists_per_page {
2827 if($self->editor->requestor) {
2828 $self->timelog("Checking for opac.lists_per_page preference");
2829 # See if the user has a lists per page preference
2830 my $ipp = $self->editor->search_actor_user_setting({
2831 usr => $self->editor->requestor->id,
2832 name => 'opac.lists_per_page'
2834 $self->timelog("Got opac.lists_per_page preference");
2835 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2837 return 10; # default
2840 sub _get_items_per_page {
2843 if($self->editor->requestor) {
2844 $self->timelog("Checking for opac.list_items_per_page preference");
2845 # See if the user has a list items per page preference
2846 my $ipp = $self->editor->search_actor_user_setting({
2847 usr => $self->editor->requestor->id,
2848 name => 'opac.list_items_per_page'
2850 $self->timelog("Got opac.list_items_per_page preference");
2851 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2853 return 10; # default
2856 sub load_myopac_bookbags {
2858 my $e = $self->editor;
2859 my $ctx = $self->ctx;
2860 my $limit = $self->_get_lists_per_page || 10;
2861 my $offset = $self->cgi->param('offset') || 0;
2863 $ctx->{bookbags_limit} = $limit;
2864 $ctx->{bookbags_offset} = $offset;
2866 # for list item pagination
2867 my $item_limit = $self->_get_items_per_page;
2868 my $item_page = $self->cgi->param('item_page') || 1;
2869 my $item_offset = ($item_page - 1) * $item_limit;
2870 $ctx->{bookbags_item_page} = $item_page;
2872 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2873 $e->xact_begin; # replication...
2875 my $rv = $self->load_mylist;
2876 unless($rv eq Apache2::Const::OK) {
2881 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2883 {owner => $e->requestor->id, btype => 'bookbag'}, {
2884 order_by => {cbreb => 'name'},
2892 if(!$ctx->{bookbags}) {
2894 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2897 # We load the user prefs to get their default bookbag.
2898 $self->_load_user_with_prefs;
2900 # We also want a total count of the user's bookbags.
2902 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2904 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2906 my $r = $e->json_query($q);
2907 $ctx->{bookbag_count} = $r->[0]->{'count'};
2909 # If the user wants a specific bookbag's items, load them.
2911 if ($self->cgi->param("bbid")) {
2913 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2916 my $query = $self->_prepare_bookbag_container_query(
2917 $bookbag->id, $sorter, $modifier
2920 # Calculate total count of the items in selected bookbag.
2921 # This total includes record entries that have no assets available.
2922 my $bb_search_results = $U->simplereq(
2923 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2924 {"limit" => 1, "offset" => 0}, $query
2925 ); # we only need the count, so do the actual search with limit=1
2927 if ($bb_search_results) {
2928 $ctx->{bb_item_count} = $bb_search_results->{count};
2930 $logger->warn("search failed in load_myopac_bookbags()");
2931 $ctx->{bb_item_count} = 0; # fallback value
2934 #calculate page count
2935 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2937 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2938 if (!$self->_update_bookbag_metadata($bookbag)) {
2940 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2943 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2946 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2947 if ($self->cgi->param($param)) {
2948 my @vals = $self->cgi->param($param);
2949 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2953 return $self->generic_redirect($url);
2957 # we're done with our CStoreEditor. Rollback here so
2958 # later calls don't cause a timeout, resulting in a
2959 # transaction rollback under the covers.
2963 # For list items pagination
2965 "limit" => $item_limit,
2966 "offset" => $item_offset
2969 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2970 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2972 # capture pref_ou for callnumber filter/display
2973 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2975 # search for local callnumbers for display
2976 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2978 my (undef, @recs) = $self->get_records_and_facets(
2979 [ map {$_->target_biblio_record_entry->id} @$items ],
2982 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2984 site => $ctx->{get_aou}->($focus_ou)->shortname,
2985 pref_lib => $ctx->{pref_ou}
2989 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2991 $bookbag->items($items);
2995 # If we have add_rec, we got here from the "Add to new list"
2996 # or "See all" popmenu items.
2997 if (my $add_rec = $self->cgi->param('add_rec')) {
2998 $self->ctx->{add_rec} = $add_rec;
2999 # But not in the staff client, 'cause that breaks things.
3000 unless ($self->ctx->{is_staff}) {
3001 # allow caller to provide the where_from in cases where
3002 # the referer is an intermediate error page
3003 if ($self->cgi->param('where_from')) {
3004 $self->ctx->{where_from} = $self->cgi->param('where_from');
3006 $self->ctx->{where_from} = $self->ctx->{referer};
3007 if ( my $anchor = $self->cgi->param('anchor') ) {
3008 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3014 # this rollback may be a dupe, but that's OK because
3015 # cstoreditor ignores dupe rollbacks
3018 return Apache2::Const::OK;
3022 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3023 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3024 sub load_myopac_bookbag_update {
3025 my ($self, $action, $list_id, @hold_recs) = @_;
3026 my $e = $self->editor;
3027 my $cgi = $self->cgi;
3029 # save_notes is effectively another action, but is passed in a separate
3030 # CGI parameter for what are really just layout reasons.
3031 $action = 'save_notes' if $cgi->param('save_notes');
3032 $action ||= $cgi->param('action');
3034 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3036 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3037 my @selected_item = $cgi->param('selected_item');
3038 my $shared = $cgi->param('shared');
3039 my $move_cart = $cgi->param('move_cart');
3040 my $name = $cgi->param('name');
3041 my $description = $cgi->param('description');
3045 # bail out if user is attempting an action that requires
3046 # that at least one list item be selected
3047 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3048 ($action eq 'place_hold' || $action eq 'print' ||
3049 $action eq 'email' || $action eq 'del_item')) {
3050 my $url = $self->ctx->{referer};
3051 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3052 return $self->generic_redirect($url);
3055 # This url intentionally leaves off the edit_notes parameter, but
3056 # may need to add some back in for paging.
3058 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3059 $self->ctx->{opac_root} . "/myopac/lists?";
3061 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3062 if ($cgi->param($param)) {
3063 my @vals = $cgi->param($param);
3064 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3068 if ($action eq 'create') {
3071 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3073 $list->description($description);
3074 $list->owner($e->requestor->id);
3075 $list->btype('bookbag');
3076 $list->pub($shared ? 't' : 'f');
3077 $success = $U->simplereq('open-ils.actor',
3078 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3079 if (ref($success) ne 'HASH') {
3080 $list_id = (ref($success)) ? $success->id : $success;
3081 if (scalar @add_rec) {
3082 foreach my $add_rec (@add_rec) {
3083 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3084 $item->bucket($list_id);
3085 $item->target_biblio_record_entry($add_rec);
3086 $success = $U->simplereq('open-ils.actor',
3087 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3088 last unless $success;
3092 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3093 foreach my $add_rec (@$list) {
3094 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3095 $item->bucket($list_id);
3096 $item->target_biblio_record_entry($add_rec);
3097 $success = $U->simplereq('open-ils.actor',
3098 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3099 last unless $success;
3101 $self->clear_anon_cache;
3104 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3107 $self->ctx->{bucket_failure_noname} = 1;
3110 } elsif($action eq 'place_hold') {
3112 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3113 my $from_basket = scalar(@hold_recs);
3114 unless (@hold_recs) {
3115 if (@selected_item) {
3116 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3117 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3121 return Apache2::Const::OK unless @hold_recs;
3122 $logger->info("placing holds from list page on: @hold_recs");
3124 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3125 $url .= ';hold_target=' . $_ for @hold_recs;
3126 $url .= ';from_basket=1' if $from_basket;
3127 foreach my $param (('loc', 'qtype', 'query')) {
3128 if ($cgi->param($param)) {
3129 my @vals = $cgi->param($param);
3130 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3133 return $self->generic_redirect($url);
3135 } elsif ($action eq 'print') {
3136 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3137 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3138 if (!$incoming_sort) {
3139 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3141 if (!$incoming_sort) {
3142 $incoming_sort = 'author';
3145 $incoming_sort =~ s/sort.*$//;
3147 $self->ctx->{sort} = $incoming_sort;
3148 $self->ctx->{sort_dir} = $sort_dir;
3150 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3151 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3152 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3153 return $self->load_mylist_print($temp_cache_key);
3154 } elsif ($action eq 'email') {
3155 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3156 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3157 if (!$incoming_sort) {
3158 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3160 if (!$incoming_sort) {
3161 $incoming_sort = 'author';
3164 $incoming_sort =~ s/sort.*$//;
3166 $self->ctx->{sort} = $incoming_sort;
3167 $self->ctx->{sort_dir} = $sort_dir;
3169 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3170 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3171 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3172 return $self->load_mylist_email($temp_cache_key);
3175 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3177 return Apache2::Const::HTTP_BAD_REQUEST unless
3178 $list and $list->owner == $e->requestor->id;
3181 if($action eq 'delete') {
3182 $success = $U->simplereq('open-ils.actor',
3183 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3185 # We check to see if we're deleting the user's default list.
3186 $self->_load_user_with_prefs;
3187 my $settings_map = $self->ctx->{user_setting_map};
3188 if ($$settings_map{'opac.default_list'} == $list_id) {
3189 # We unset the user's opac.default_list setting.
3190 $success = $U->simplereq(
3192 'open-ils.actor.patron.settings.update',
3195 { 'opac.default_list' => 0 }
3199 } elsif($action eq 'show') {
3200 unless($U->is_true($list->pub)) {
3202 $success = $U->simplereq('open-ils.actor',
3203 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3206 } elsif($action eq 'hide') {
3207 if($U->is_true($list->pub)) {
3209 $success = $U->simplereq('open-ils.actor',
3210 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3213 } elsif($action eq 'rename') {
3216 $success = $U->simplereq('open-ils.actor',
3217 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3220 } elsif($action eq 'add_rec') {
3221 foreach my $add_rec (@add_rec) {
3222 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3223 $item->bucket($list_id);
3224 $item->target_biblio_record_entry($add_rec);
3225 $success = $U->simplereq('open-ils.actor',
3226 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3227 last unless $success;
3229 # Redirect back where we came from if we have an anchor parameter:
3230 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3231 $url = $self->ctx->{referer};
3232 $url =~ s/#.*|$/#$anchor/;
3233 } elsif ($cgi->param('where_from')) {
3234 # Or, if we have a "where_from" parameter.
3235 $url = $cgi->param('where_from');
3237 } elsif ($action eq 'del_item') {
3238 foreach (@selected_item) {
3239 $success = $U->simplereq(
3241 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3243 last unless $success;
3245 } elsif ($action eq 'save_notes') {
3246 $success = $self->update_bookbag_item_notes;
3247 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3248 } elsif ($action eq 'make_default') {
3249 $success = $U->simplereq(
3251 'open-ils.actor.patron.settings.update',
3254 { 'opac.default_list' => $list_id }
3256 } elsif ($action eq 'remove_default') {
3257 $success = $U->simplereq(
3259 'open-ils.actor.patron.settings.update',
3262 { 'opac.default_list' => 0 }
3266 return $self->generic_redirect($url) if $success;
3268 $self->ctx->{where_from} = $cgi->param('where_from');
3269 $self->ctx->{bucket_action} = $action;
3270 $self->ctx->{bucket_action_failed} = 1;
3271 return Apache2::Const::OK;
3274 sub update_bookbag_item_notes {
3276 my $e = $self->editor;
3278 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3279 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3281 # We're going to leverage an API call that's already been written to check
3282 # permissions appropriately.
3284 my $a = create OpenSRF::AppSession("open-ils.actor");
3285 my $method = "open-ils.actor.container.item_note.cud";
3287 for my $note_key (@note_keys) {
3290 my $id = ($note_key =~ /(\d+)/)[0];
3293 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3294 my $event = $e->die_event;
3295 $self->apache->log->warn(
3296 "error retrieving cbrebin id $id, got event " .
3300 $self->ctx->{bucket_action_event} = $event;
3304 if (length($self->cgi->param($note_key))) {
3305 $note->ischanged(1);
3306 $note->note($self->cgi->param($note_key));
3308 $note->isdeleted(1);
3311 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3313 if (defined $U->event_code($r)) {
3314 $self->apache->log->warn(
3315 "attempt to modify cbrebin " . $note->id .
3316 " returned event " . $r->{textcode}
3320 $self->ctx->{bucket_action_event} = $r;
3325 for my $item_key (@item_keys) {
3326 my $id = int(($item_key =~ /(\d+)/)[0]);
3327 my $text = $self->cgi->param($item_key);
3330 next unless length $text;
3332 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3337 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3339 if (defined $U->event_code($r)) {
3340 $self->apache->log->warn(
3341 "attempt to create cbrebin for item " . $note->item .
3342 " returned event " . $r->{textcode}
3346 $self->ctx->{bucket_action_event} = $r;
3355 sub load_myopac_bookbag_print {
3358 my $id = int($self->cgi->param("list"));
3360 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3363 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3367 # Get the bookbag object itself, assuming we're allowed to.
3368 if ($self->editor->allowed("VIEW_CONTAINER")) {
3370 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3372 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3376 "owner" => $self->editor->requestor->id,
3380 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3382 $bbag = pop @$bookbags;
3385 # If we have a bookbag we're allowed to look at, issue the A/T event
3386 # to get CSV, passing as a user param that search query we built before.
3388 $self->ctx->{csv} = $U->fire_object_event(
3389 undef, "container.biblio_record_entry_bucket.csv",
3390 $bbag, $self->editor->requestor->home_ou,
3391 undef, {"item_search" => $item_search}
3395 # Create a reasonable filename and set the content disposition to
3396 # provoke browser download dialogs.
3397 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3399 return $self->set_file_download_headers("$filename.csv");
3402 sub load_myopac_circ_history_export {
3404 my $e = $self->editor;
3405 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3407 my $circs = $self->fetch_user_circ_history(1);
3409 $self->ctx->{csv}->{circs} = $circs;
3410 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3414 sub load_myopac_reservations {
3416 my $e = $self->editor;
3417 my $ctx = $self->ctx;
3419 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3420 $e->authtoken, undef
3423 $ctx->{reservations} = $upcoming;
3424 return Apache2::Const::OK;
3428 sub load_password_reset {
3430 my $cgi = $self->cgi;
3431 my $ctx = $self->ctx;
3432 my $barcode = $cgi->param('barcode');
3433 my $username = $cgi->param('username');
3434 my $email = $cgi->param('email');
3435 my $pwd1 = $cgi->param('pwd1');
3436 my $pwd2 = $cgi->param('pwd2');
3437 my $uuid = $ctx->{page_args}->[0];
3441 $logger->info("patron password reset with uuid $uuid");
3443 if ($pwd1 and $pwd2) {
3445 if ($pwd1 eq $pwd2) {
3447 my $response = $U->simplereq(
3449 'open-ils.actor.patron.password_reset.commit',
3452 $logger->info("patron password reset response " . Dumper($response));
3454 if ($U->event_code($response)) { # non-success event
3456 my $code = $response->{textcode};
3458 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3459 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3462 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3463 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3468 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3471 } else { # passwords not equal
3473 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3476 } else { # 2 password values needed
3478 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3481 } elsif ($barcode or $username) {
3483 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3484 push(@params, $email) if $email;
3488 'open-ils.actor.patron.password_reset.request', @params);
3490 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3493 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3494 return Apache2::Const::OK;