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 locale billing_address waiver_entries stat_cat_entries/, @extra_flesh],
41 "aou" => ["billing_address"],
42 "actscecm" => ["stat_cat"]
47 $e->rollback if $local_xact;
49 $self->ctx->{user}->wsid($usr->wsid);
50 $self->ctx->{user}->ws_ou($usr->ws_ou);
52 # discard replaced (negative-id) addresses.
53 $self->ctx->{user}->addresses([
54 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
56 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
57 unless $self->ctx->{user};
62 # Given an event returned by a failed attempt to create a hold, do we have
63 # permission to override? XXX Should the permission check be scoped to a
64 # given org_unit context?
65 sub test_could_override {
66 my ($self, $event) = @_;
68 return 0 unless $event;
69 return 1 if $self->editor->allowed($event->{textcode} . ".override");
70 return 1 if $event->{"fail_part"} and
71 $self->editor->allowed($event->{"fail_part"} . ".override");
75 # Find out whether we care that local copies are available
76 sub local_avail_concern {
77 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
79 my $would_block = $self->ctx->{get_org_setting}->
80 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
82 $self->ctx->{get_org_setting}->
83 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
84 not $self->cgi->param("override")
85 ) unless $would_block;
87 if ($would_block or $would_alert) {
89 "hold_target" => $hold_target,
90 "hold_type" => $hold_type,
91 "org_unit" => $pickup_lib
93 my $local_avail = $U->simplereq(
95 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
98 "copy availability information for " . Dumper($args) .
99 " is " . Dumper($local_avail)
101 if (%$local_avail) { # if hash not empty
102 $self->ctx->{hold_copy_available} = $local_avail;
103 return ($would_block, $would_alert);
111 # user : au object, fleshed
112 sub load_myopac_prefs {
114 my $cgi = $self->cgi;
115 my $e = $self->editor;
116 my $pending_addr = $cgi->param('pending_addr');
117 my $replace_addr = $cgi->param('replace_addr');
118 my $delete_pending = $cgi->param('delete_pending');
120 $self->prepare_extended_user_info;
121 my $user = $self->ctx->{user};
123 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
124 if(defined($lock_usernames) and $lock_usernames == 1) {
125 # Policy says no username changes
126 $self->ctx->{username_change_disallowed} = 1;
128 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
129 if(!$username_unlimit) {
130 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
132 # Default is "starts with a number"
133 $regex_check = '^\d+';
135 # You already have a username?
136 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
137 $self->ctx->{username_change_disallowed} = 1;
142 return Apache2::Const::OK unless
143 $pending_addr or $replace_addr or $delete_pending;
145 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
148 if( $pending_addr ) { # update an existing pending address
150 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
151 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
152 $paddr->$_( $cgi->param($_) ) for @form_fields;
154 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
156 $paddr = Fieldmapper::actor::user_address->new;
158 $paddr->usr($user->id);
159 $paddr->pending('t');
160 $paddr->replaces($replace_addr);
161 $paddr->$_( $cgi->param($_) ) for @form_fields;
163 } elsif( $delete_pending ) {
164 $paddr = $e->retrieve_actor_user_address($delete_pending);
165 return Apache2::Const::HTTP_BAD_REQUEST unless
166 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
167 $paddr->isdeleted(1);
170 my $resp = $U->simplereq(
172 'open-ils.actor.user.address.pending.cud',
173 $e->authtoken, $paddr);
175 if( $U->event_code($resp) ) {
176 $logger->error("Error updating pending address: $resp");
177 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
180 # in light of these changes, re-fetch latest data
182 $self->prepare_extended_user_info;
185 return Apache2::Const::OK;
188 sub load_myopac_prefs_notify {
190 my $e = $self->editor;
193 my $stat = $self->_load_user_with_prefs;
194 return $stat if $stat;
196 my $user_prefs = $self->fetch_optin_prefs;
197 $user_prefs = $self->update_optin_prefs($user_prefs)
198 if $self->cgi->request_method eq 'POST';
200 $self->ctx->{opt_in_settings} = $user_prefs;
202 return Apache2::Const::OK
203 unless $self->cgi->request_method eq 'POST';
206 my $set_map = $self->ctx->{user_setting_map};
210 opac.default_sms_notify
212 my $val = $self->cgi->param($key);
213 $settings{$key}= $val unless $$set_map{$key} eq $val;
216 my $key = 'opac.default_sms_carrier';
217 my $val = $self->cgi->param('sms_carrier');
218 $settings{$key}= $val unless $$set_map{$key} eq $val;
220 $key = 'opac.hold_notify';
221 my @notify_methods = ();
222 if ($self->cgi->param($key . ".email") eq 'on') {
223 push @notify_methods, "email";
225 if ($self->cgi->param($key . ".phone") eq 'on') {
226 push @notify_methods, "phone";
228 if ($self->cgi->param($key . ".sms") eq 'on') {
229 push @notify_methods, "sms";
231 $val = join("|",@notify_methods);
232 $settings{$key}= $val unless $$set_map{$key} eq $val;
234 # Send the modified settings off to be saved
237 'open-ils.actor.patron.settings.update',
238 $self->editor->authtoken, undef, \%settings);
240 # re-fetch user prefs
241 $self->ctx->{updated_user_settings} = \%settings;
243 # update holds: check if any changes affect any holds
244 my @llchgs = $self->_parse_prefs_notify_hold_related();
247 if ( $self->cgi->param('hasHoldsChanges') ) {
248 # propagate pref_notify changes to holds
249 for my $chset (@llchgs){
250 # FIXME is this still needed?
255 my $holds = $U->simplereq('open-ils.circ', 'open-ils.circ.holds.retrieve.by_usr.with_notify',
256 $e->authtoken, $e->requestor->id);
260 my $default_phone_changes = {};
261 my $sms_changes = {};
265 for my $chset (@llchgs) {
266 next if scalar(@$chset) < 3;
267 my ($old, $new, $field) = @$chset;
269 my $bool = $field =~ /_notify/ ? 1 : 0;
271 # find holds that would change
273 foreach my $hold (@$holds) {
274 if ($field eq 'email_notify') {
275 my $curr = $hold->{$field} eq 't' ? 'true' : 'false';
276 push @$affected, $hold if $curr ne $new;
277 } elsif ($field eq 'default_phone') {
278 my $old_phone = $hold->{phone_notify} // '';
279 $new_phone = $new // '';
280 push @{ $default_phone_changes->{ $old_phone } }, $hold->{id}
281 if $old_phone ne $new_phone;
282 } elsif ($field eq 'phone_notify') {
283 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
284 push @$affected, $hold if $curr ne $new;
285 } elsif ($field eq 'sms_notify') {
286 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
287 push @$affected, $hold if $curr ne $new;
288 } elsif ($field eq 'sms_info') {
289 my $old_carrier = $hold->{'sms_carrier'} // '';
290 my $old_sms = $hold->{'sms_notify'} // '';
291 $new_carrier = $new->{carrier} // '';
292 $new_sms = $new->{sms} // '';
293 if (!($old_carrier eq $new_carrier && $old_sms eq $new_sms)) {
294 push @{ $sms_changes->{ join("\t", $old_carrier, $old_sms) } }, $hold->{id};
299 # append affected array to chset
300 if (scalar(@$affected) > 0){
301 push(@$chset, [ map { $_->{id} } @$affected ]);
302 push(@ffectedChgs, $chset);
307 foreach my $old_phone (keys %$default_phone_changes) {
308 push(@ffectedChgs, [ $old_phone, $new_phone, 'default_phone', $default_phone_changes->{$old_phone} ]);
310 foreach my $old_sms_info (keys %$sms_changes) {
311 my ($old_carrier, $old_sms) = split /\t/, $old_sms_info;
313 { carrier => $old_carrier, sms => $old_sms },
314 { carrier => $new_carrier, sms => $new_sms },
316 $sms_changes->{$old_sms_info}
320 if ( scalar(@ffectedChgs) ){
321 $self->ctx->{affectedChgs} = \@ffectedChgs;
326 return $self->_load_user_with_prefs || Apache2::Const::OK;
329 sub _parse_prefs_notify_hold_related {
332 my $for_update = shift;
334 # create an array of change arrays
337 my @phone_notify = $self->cgi->multi_param('phone_notify[]');
338 push(@chgs, \@phone_notify) if scalar(@phone_notify);
340 my $turning_on_phone_notify = !$for_update &&
341 scalar(@phone_notify) &&
342 $phone_notify[1] eq 'true';
343 my $turning_off_phone_notify = !$for_update &&
344 scalar(@phone_notify) &&
345 $phone_notify[1] eq 'false';
347 my $changing_default_phone = 0;
348 if (!$turning_off_phone_notify) {
349 my @default_phone = $self->cgi->multi_param('default_phone[]');
351 while (scalar(@default_phone) > 0) {
352 my $chg = [ splice(@default_phone, 0, 4) ];
353 if (scalar(@default_phone) > 0 && $default_phone[0] eq 'on') {
354 push @$chg, shift(@default_phone);
356 $changing_default_phone = 1;
360 if (scalar(@default_phone)) {
361 push @chgs, \@default_phone;
362 $changing_default_phone = 1;
367 if ($turning_on_phone_notify && $changing_default_phone) {
368 # we don't need to have both the phone_notify and default_phone
369 # changes; the latter will suffice
370 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
371 } elsif ($turning_on_phone_notify && !$changing_default_phone) {
372 # replace the phone_notify change with a default_phone change
373 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
374 my $default_phone = $self->cgi->param('opac.default_phone'); # we assume this is set
375 push @chgs, [ '', $default_phone, 'default_phone' ];
379 # ... since both carrier and number are needed to send an SMS notifcation,
380 # we need to treat the pair as a unit
381 my @sms_notify = $self->cgi->multi_param('sms_notify[]');
382 push(@chgs, \@sms_notify) if scalar(@sms_notify);
384 my $turning_on_sms_notify = !$for_update &&
385 scalar(@sms_notify) &&
386 $sms_notify[1] eq 'true';
387 my $turning_off_sms_notify = !$for_update &&
388 scalar(@sms_notify) &&
389 $sms_notify[1] eq 'false';
391 my $changing_sms_info = 0;
392 if (!$turning_off_sms_notify) {
393 my @sms_carrier = $self->cgi->multi_param('default_sms_carrier_id[]');
394 my @sms = $self->cgi->multi_param('default_sms[]');
396 if (scalar(@sms) || scalar(@sms_carrier)) {
397 my $new_carrier = scalar(@sms_carrier) ? $sms_carrier[1] : $self->cgi->param('sms_carrier');
398 my $new_sms = scalar(@sms) ? $sms[1] : $self->cgi->param('opac.default_sms_notify');
400 { carrier => '', sms => '' },
401 { carrier => $new_carrier, sms => $new_sms },
404 $changing_sms_info = 1;
408 my @sms_info = $self->cgi->multi_param('sms_info[]'); # only sent by confirmation page
409 if (scalar(@sms_info)) {
410 while (scalar(@sms_info) > 0) {
411 my $chg = [ splice(@sms_info, 0, 4) ];
412 if (scalar(@sms_info) > 0 && $sms_info[0] eq 'on') {
413 push @$chg, shift(@sms_info);
414 my ($carrier, $sms) = split /,/, $chg->[0], -1;
415 $chg->[0] = { carrier => $carrier, sms => $sms };
416 ($carrier, $sms) = split /,/, $chg->[1], -1;
417 $chg->[1] = { carrier => $carrier, sms => $sms };
419 $changing_sms_info = 1;
424 if ($turning_on_sms_notify && $changing_sms_info) {
425 # we don't need to have both the sms_notify and sms_info
426 # changes; the latter will suffice
427 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
428 } elsif ($turning_on_sms_notify && !$changing_sms_info) {
429 # replace the sms_notify change with a sms_info change
430 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
432 carrier => $self->cgi->param('sms_carrier'),
433 sms => $self->cgi->param('opac.default_sms_notify'),
435 push @chgs, [ { carrier => '', sms => ''}, $sms_info, 'sms_info' ];
438 my @email_notify = $self->cgi->multi_param('email_notify[]');
439 push(@chgs, \@email_notify) if scalar(@email_notify);
442 # if we're updating, keep only the ones that have been
443 # explicitly checked by the user
444 @chgs = grep { scalar(@$_) == 5 && $_->[4] eq 'on' } @chgs;
449 sub load_myopac_prefs_notify_changed_holds {
451 my $e = $self->editor;
453 my $hasChanges = $self->cgi->param('hasHoldsChanges');
455 return $self->_load_user_with_prefs || Apache2::Const::OK unless $hasChanges;
457 my @ll = $self->_parse_prefs_notify_hold_related(1);
461 my ($old, $new, $type, $holdids, $doit) = @$chset;
462 next if $doit ne 'on';
464 # parse string list into array list
465 my @holdids = split(',', $holdids);
467 if ($type =~ /_notify/){
468 # translate true/false string into 1/0
469 $old = $old eq 'true' ? 1 : 0;
470 $new = $new eq 'true' ? 1 : 0;
474 if ($type eq 'sms_info') {
475 if ($new->{carrier} eq '' && $new->{sms} eq '') {
476 # clear SMS number first to avoid check contrainst issue
477 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
478 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
479 push (@updates, $update) if (scalar(@$update) > 0);
480 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
481 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
482 push (@updates, $update) if (scalar(@$update) > 0);
484 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
485 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
486 push (@updates, $update) if (scalar(@$update) > 0);
487 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
488 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
489 push (@updates, $update) if (scalar(@$update) > 0);
492 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
493 $e->authtoken, $e->requestor->id, [@holdids], $old, $new, $type);
495 # append affected array to chset
496 if (scalar(@$update) > 0){
497 push(@updates, $update);
502 $self->ctx->{'updated'} = \@updates;
504 return $self->_load_user_with_prefs || Apache2::Const::OK;
508 sub fetch_optin_prefs {
510 my $e = $self->editor;
512 # fetch all of the opt-in settings the user has access to
513 # XXX: user's should in theory have options to opt-in to notices
514 # for remote locations, but that opens the door for a large
515 # set of generally un-used opt-ins.. needs discussion
516 my $opt_ins = $U->simplereq(
518 'open-ils.actor.event_def.opt_in.settings.atomic',
519 $e->authtoken, $e->requestor->home_ou);
521 # some opt-ins are staff-only
522 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
524 # fetch user setting values for each of the opt-in settings
525 my $user_set = $U->simplereq(
527 'open-ils.actor.patron.settings.retrieve',
530 [map {$_->name} @$opt_ins]
533 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
536 sub load_myopac_messages {
538 my $e = $self->editor;
539 my $ctx = $self->ctx;
540 my $cgi = $self->cgi;
542 my $limit = $cgi->param('limit') || 20;
543 my $offset = $cgi->param('offset') || 0;
545 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
548 my $action = $cgi->param('action') || '';
550 my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
551 if ($changed > 0 || $failed > 0) {
552 $ctx->{message_update_action} = $action;
553 $ctx->{message_update_changed} = $changed;
554 $ctx->{message_update_failed} = $failed;
555 $self->update_dashboard_stats();
559 my $single = $cgi->param('single') || 0;
560 my $id = $cgi->param('message_id');
564 if (!$action && $single && $id) {
565 $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
566 if (scalar(@$messages) == 1) {
567 $ctx->{display_single_message} = 1;
568 $ctx->{patron_message_id} = $id;
574 # fetch all the messages
575 ($ctx->{patron_messages_count}, $messages) =
576 $self->_fetch_user_messages($pcrud, $offset, $limit);
581 foreach my $aum (@$messages) {
583 push @{ $ctx->{patron_messages} }, {
585 title => $aum->title,
586 message => $aum->message,
587 create_date => $aum->create_date,
588 edit_date => $aum->edit_date,
589 is_read => defined($aum->read_date) ? 1 : 0,
590 library => $aum->sending_lib->name,
594 $ctx->{patron_messages_limit} = $limit;
595 $ctx->{patron_messages_offset} = $offset;
597 return Apache2::Const::OK;
600 sub _fetch_and_mark_read_single_message {
605 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
606 my $messages = $pcrud->request(
607 'open-ils.pcrud.search.auml.atomic',
608 $self->editor->authtoken,
610 usr => $self->editor->requestor->id,
616 flesh_fields => { auml => ['sending_lib'] },
620 $messages->[0]->read_date('now');
622 'open-ils.pcrud.update.auml',
623 $self->editor->authtoken,
627 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
629 $self->update_dashboard_stats();
634 sub _fetch_user_messages {
640 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
642 my $all_messages = $pcrud->request(
643 'open-ils.pcrud.id_list.auml.atomic',
644 $self->editor->authtoken,
646 usr => $self->editor->requestor->id,
652 my $messages = $pcrud->request(
653 'open-ils.pcrud.search.auml.atomic',
654 $self->editor->authtoken,
656 usr => $self->editor->requestor->id,
661 flesh_fields => { auml => ['sending_lib'] },
662 order_by => { auml => 'create_date DESC' },
667 return scalar(@$all_messages), $messages;
670 sub _handle_message_action {
674 my $cgi = $self->cgi;
676 my @ids = $cgi->param('message_id');
677 return (0, 0) unless @ids;
681 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
683 my $aum = $pcrud->request(
684 'open-ils.pcrud.retrieve.auml',
685 $self->editor->authtoken,
689 if ($action eq 'mark_read') {
690 $aum->read_date('now');
691 } elsif ($action eq 'mark_unread') {
692 $aum->clear_read_date();
693 } elsif ($action eq 'mark_deleted') {
696 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
701 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
703 $failed = scalar(@ids);
705 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
707 return ($changed, $failed);
710 sub _load_lists_and_settings {
712 my $e = $self->editor;
713 my $stat = $self->_load_user_with_prefs;
716 my $setting_map = $self->ctx->{user_setting_map};
717 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
718 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
720 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
721 order_by => {cbreb => 'name'},
722 limit => $self->cgi->param('limit') || 10,
723 offset => $self->cgi->param('offset') || 0
727 # We also want a total count of the user's bookbags.
729 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
731 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
733 my $r = $e->json_query($q);
734 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
735 # Someone has requested that we use the default list's name
736 # rather than "Default List."
739 'select' => {'cbreb' => ['name']},
741 'where' => {'id' => $exclude}
743 $r = $e->json_query($q);
744 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
752 sub update_optin_prefs {
754 my $user_prefs = shift;
755 my $e = $self->editor;
756 my @settings = $self->cgi->param('setting');
759 # apply now-true settings
760 for my $applied (@settings) {
761 # see if setting is already applied to this user
762 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
763 $newsets{$applied} = OpenSRF::Utils::JSON->true;
766 # remove now-false settings
767 for my $pref (grep { $_->{value} } @$user_prefs) {
768 $newsets{$pref->{cust}->name} = undef
769 unless grep { $_ eq $pref->{cust}->name } @settings;
774 'open-ils.actor.patron.settings.update',
775 $e->authtoken, $e->requestor->id, \%newsets);
777 # update the local prefs to match reality
778 for my $pref (@$user_prefs) {
779 $pref->{value} = $newsets{$pref->{cust}->name}
780 if exists $newsets{$pref->{cust}->name};
786 sub _load_user_with_prefs {
788 my $stat = $self->prepare_extended_user_info('settings');
789 return $stat if $stat; # not-OK
791 $self->ctx->{user_setting_map} = {
792 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
793 @{$self->ctx->{user}->settings}
799 sub _get_bookbag_sort_params {
800 my ($self, $param_name) = @_;
802 # The interface that feeds this cgi parameter will provide a single
803 # argument for a QP sort filter, and potentially a modifier after a period.
804 # In practice this means the "sort" parameter will be something like
805 # "titlesort" or "authorsort.descending".
806 my $sorter = $self->cgi->param($param_name) || "";
809 $sorter =~ s/^(.*?)\.(.*)/$1/;
810 $modifier = $2 || undef;
813 return ($sorter, $modifier);
816 sub _prepare_bookbag_container_query {
817 my ($self, $container_id, $sorter, $modifier) = @_;
820 "container(bre,bookbag,%d,%s)%s%s",
821 $container_id, $self->editor->authtoken,
822 ($sorter ? " sort($sorter)" : ""),
823 ($modifier ? "#$modifier" : "")
827 sub _prepare_anonlist_sorting_query {
828 my ($self, $list, $sorter, $modifier) = @_;
831 "record_list(%s)%s%s",
833 ($sorter ? " sort($sorter)" : ""),
834 ($modifier ? "#$modifier" : "")
839 sub load_myopac_prefs_settings {
844 opac.default_search_location
845 opac.default_pickup_location
846 opac.temporary_list_no_warn
849 my $stat = $self->_load_user_with_prefs;
850 return $stat if $stat;
852 # if behind-desk holds are supported and the user
853 # setting which controls the value is opac-visible,
854 # add the setting to the list of settings to manage.
855 # note: this logic may need to be changed later to
856 # check whether behind-the-desk holds are supported
857 # anywhere the patron may select as a pickup lib.
858 my $e = $self->editor;
859 my $bdous = $self->ctx->{get_org_setting}->(
860 $e->requestor->home_ou,
861 'circ.holds.behind_desk_pickup_supported');
865 $e->retrieve_config_usr_setting_type(
866 'circ.holds_behind_desk');
868 if ($U->is_true($setting->opac_visible)) {
869 push(@user_prefs, 'circ.holds_behind_desk');
870 $self->ctx->{behind_desk_supported} = 1;
874 my $use_privacy_waiver = $self->ctx->{get_org_setting}->(
875 $e->requestor->home_ou, 'circ.privacy_waiver');
877 return Apache2::Const::OK
878 unless $self->cgi->request_method eq 'POST';
880 # some setting values from the form don't match the
881 # required value/format for the db, so they have to be
882 # individually translated.
885 my $set_map = $self->ctx->{user_setting_map};
887 foreach my $key (@user_prefs) {
888 my $val = $self->cgi->param($key);
889 $settings{$key}= $val unless $$set_map{$key} eq $val;
892 # Used by the settings update form when warning on history delete.
893 my $clear_circ_history = 0;
894 my $clear_hold_history = 0;
896 # true if we need to show the warning on next page load.
897 my $hist_warning_needed = 0;
898 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
900 my $now = DateTime->now->strftime('%F');
902 qw/history.circ.retention_start history.hold.retention_start/) {
904 my $val = $self->cgi->param($key);
905 if($val and $val eq 'on') {
906 # Set the start time to 'now' unless a start time already exists for the user
907 $settings{$key} = $now unless $$set_map{$key};
911 next unless $$set_map{$key}; # nothing to do
913 $clear_circ_history = 1 if $key =~ /circ/;
914 $clear_hold_history = 1 if $key =~ /hold/;
916 if (!$hist_clear_confirmed) {
917 # when clearing circ history, only warn if history data exists.
919 if ($clear_circ_history) {
921 if ($self->fetch_user_circ_history(0, 1)->[0]) {
922 $hist_warning_needed = 1;
923 next; # no history updates while confirmation pending
928 my $one_hold = $e->json_query({
932 transform => 'action.usr_visible_holds',
937 where => {id => $e->requestor->id},
942 $hist_warning_needed = 1;
943 next; # no history updates while confirmation pending
948 $settings{$key} = undef;
950 if ($key eq 'history.circ.retention_start') {
951 # delete existing circulation history data.
954 'open-ils.actor.history.circ.clear',
955 $self->editor->authtoken);
960 # Warn patrons before clearing circ/hold history
961 if ($hist_warning_needed) {
962 $self->ctx->{clear_circ_history} = $clear_circ_history;
963 $self->ctx->{clear_hold_history} = $clear_hold_history;
964 $self->ctx->{confirm_history_delete} = 1;
967 # Send the modified settings off to be saved
970 'open-ils.actor.patron.settings.update',
971 $self->editor->authtoken, undef, \%settings);
973 $self->ctx->{updated_user_settings} = \%settings;
975 if ($use_privacy_waiver) {
977 my $saved_entries = ();
978 my @waiver_types = qw/place_holds pickup_holds checkout_items view_history/;
980 # initialize our waiver hash with waiver IDs from hidden input
981 # (this ensures that we capture entries with no checked boxes)
982 foreach my $waiver_row_id ($self->cgi->param("waiver_id")) {
983 $waiver{$waiver_row_id} = {};
986 # process our waiver checkboxes into a hash, keyed by waiver ID
987 # (a new entry, if any, has id = 'new')
988 foreach my $waiver_type (@waiver_types) {
989 if ($self->cgi->param("waiver_$waiver_type")) {
990 foreach my $waiver_id ($self->cgi->param("waiver_$waiver_type")) {
991 # ensure this waiver exists in our hash
992 $waiver{$waiver_id} = {} if !$waiver{$waiver_id};
993 $waiver{$waiver_id}->{$waiver_type} = 1;
998 foreach my $k (keys %waiver) {
1000 # get name from textbox
1001 $w->{name} = $self->cgi->param("waiver_name_$k");
1003 foreach (@waiver_types) {
1004 $w->{$_} = 0 unless ($w->{$_});
1006 push @$saved_entries, $w;
1009 # update patron privacy waiver entries
1012 'open-ils.actor.patron.privacy_waiver.update',
1013 $self->editor->authtoken, undef, $saved_entries);
1015 $self->ctx->{updated_waiver_entries} = $saved_entries;
1018 # re-fetch user prefs
1019 return $self->_load_user_with_prefs || Apache2::Const::OK;
1022 sub load_myopac_prefs_my_lists {
1025 my @user_prefs = qw/
1027 opac.list_items_per_page
1030 my $stat = $self->_load_user_with_prefs;
1031 return $stat if $stat;
1033 return Apache2::Const::OK
1034 unless $self->cgi->request_method eq 'POST';
1037 my $set_map = $self->ctx->{user_setting_map};
1039 foreach my $key (@user_prefs) {
1040 my $val = $self->cgi->param($key);
1041 $settings{$key}= $val unless $$set_map{$key} eq $val;
1044 if (keys %settings) { # we found a different setting value
1045 # Send the modified settings off to be saved
1048 'open-ils.actor.patron.settings.update',
1049 $self->editor->authtoken, undef, \%settings);
1051 # re-fetch user prefs
1052 $self->ctx->{updated_user_settings} = \%settings;
1053 $stat = $self->_load_user_with_prefs;
1056 return $stat || Apache2::Const::OK;
1059 sub fetch_user_holds {
1061 my $hold_ids = shift;
1062 my $ids_only = shift;
1064 my $available = shift;
1068 my $e = $self->editor;
1069 my $all_ids; # to be used below.
1072 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1074 $hold_ids = $circ->request(
1075 'open-ils.circ.holds.id_list.retrieve.authoritative',
1082 $all_ids = $hold_ids;
1083 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
1086 $all_ids = $hold_ids;
1089 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
1092 suppress_notices => 1,
1093 suppress_transits => 1,
1095 suppress_patron_details => 1
1098 # ----------------------------------------------------------------
1099 # Collect holds in batches of $batch_size for faster retrieval
1103 my $mk_req_batch = sub {
1105 my $top_idx = $batch_idx + $batch_size;
1106 while($batch_idx < $top_idx) {
1107 my $hold_id = $hold_ids->[$batch_idx++];
1108 last unless $hold_id;
1109 my $ses = OpenSRF::AppSession->create('open-ils.circ');
1110 my $req = $ses->request(
1111 'open-ils.circ.hold.details.retrieve',
1112 $e->authtoken, $hold_id, $args);
1113 push(@ses, {ses => $ses, req => $req});
1119 my(@collected, @holds, @ses);
1122 @ses = $mk_req_batch->() if $first;
1123 last if $first and not @ses;
1126 while(my $blob = pop(@collected)) {
1129 # in the holds edit UI, we need to know what formats and
1130 # languages the user selected for this hold, plus what
1131 # formats/langs are available on the MR as a whole.
1132 if ($blob->{hold}{hold}->hold_type eq 'M') {
1133 my $hold = $blob->{hold}->{hold};
1135 # for MR, fetch the combined MR unapi blob
1136 (undef, @data) = $self->get_records_and_facets(
1137 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
1139 my $filter_org = $U->org_unit_ancestor_at_depth(
1140 $hold->selection_ou,
1141 $hold->selection_depth);
1143 my $filter_data = $U->simplereq(
1145 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
1146 $hold->target, $filter_org, [$hold->id]
1149 $blob->{metarecord_filters} =
1150 $filter_data->[0]->{metarecord};
1151 $blob->{metarecord_selected_filters} =
1152 $filter_data->[1]->{hold};
1155 (undef, @data) = $self->get_records_and_facets(
1156 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
1160 $blob->{marc_xml} = $data[0]->{marc_xml};
1161 push(@holds, $blob);
1165 for my $req_data (@ses) {
1166 push(@collected, {hold => $req_data->{req}->gather(1)});
1167 $req_data->{ses}->kill_me;
1170 @ses = $mk_req_batch->();
1171 last unless @collected or @ses;
1175 # put the holds back into the original server sort order
1177 for my $id (@$hold_ids) {
1178 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1182 try { # if the service is not running, just let this fail silently
1183 $curbsides = $U->simplereq(
1184 'open-ils.curbside',
1185 'open-ils.curbside.fetch_mine.atomic',
1188 } catch Error with {};
1190 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, curbsides => $curbsides };
1193 sub load_current_curbside_libs {
1195 my $ctx = $self->ctx;
1196 my $e = $self->editor;
1197 my $holds = $e->search_action_hold_request({
1198 usr => $e->requestor->id,
1199 shelf_time => { '!=' => undef },
1200 cancel_time => undef,
1201 fulfillment_time => undef
1205 for my $h (@$holds) {
1206 next if ($h->pickup_lib != $h->current_shelf_lib);
1207 $pickup_libs{$h->pickup_lib} = 1;
1210 my @curbside_pickup_libs;
1211 for my $pul (keys %pickup_libs) {
1212 push(@curbside_pickup_libs, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1215 $ctx->{curbside_pickup_libs} = [
1216 sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } @curbside_pickup_libs
1220 sub handle_hold_update {
1223 my $hold_ids = shift;
1224 my $e = $self->editor;
1225 my $ctx = $self->ctx;
1228 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1229 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1231 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1233 if($action =~ /cancel/) {
1235 for my $hold_id (@hold_ids) {
1236 my $resp = $circ->request(
1237 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1240 } elsif ($action =~ /activate|suspend/) {
1243 for my $hold_id (@hold_ids) {
1244 my $vals = {id => $hold_id};
1246 if($action =~ /activate/) {
1247 $vals->{frozen} = 'f';
1248 $vals->{thaw_date} = undef;
1250 } elsif($action =~ /suspend/) {
1251 $vals->{frozen} = 't';
1252 # $vals->{thaw_date} = TODO;
1254 push(@$vlist, $vals);
1257 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1258 $self->ctx->{hold_suspend_post_capture} = 1 if
1259 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1261 } elsif ($action eq 'edit') {
1264 my $val = {"id" => $_};
1265 $val->{"frozen"} = $self->cgi->param("frozen");
1266 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1267 $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1268 $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1269 $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1270 $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1272 for my $field (qw/expire_time thaw_date/) {
1273 # XXX TODO make this support other date formats, not just
1275 next unless $self->cgi->param($field) =~
1276 m:^(\d{2})/(\d{2})/(\d{4})$:;
1277 $val->{$field} = "$3-$1-$2";
1280 $val->{holdable_formats} = # no-op for non-MR holds
1281 $self->compile_holdable_formats(undef, $_);
1287 'open-ils.circ.hold.update.batch.atomic',
1288 $e->authtoken, undef, \@vals
1289 )->gather(1); # LFW XXX test for failure
1290 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1291 foreach my $param (('loc', 'qtype', 'query')) {
1292 if ($self->cgi->param($param)) {
1293 my @vals = $self->cgi->param($param);
1294 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1297 } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1300 $circ = OpenSRF::AppSession->create('open-ils.curbside');
1302 # see what we're doing with curbside here...
1303 my $cs_action = $self->cgi->param("cs_action");
1304 my $slot_id = $self->cgi->param("cs_slot_id");
1306 # we have an id, let's grab it if we can
1307 my $slot = $e->retrieve_action_curbside($slot_id);
1308 $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1310 my $org = $self->cgi->param("cs_org");
1311 my $date = $self->cgi->param("cs_date");
1312 my $time = $self->cgi->param("cs_time");
1313 my $notes = $self->cgi->param("cs_notes");
1316 $org ||= $slot->org;
1317 $notes ||= $slot->notes;
1319 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1320 $date ||= $dt->strftime('%F');
1321 $time ||= $dt->strftime('%T');
1325 $ctx->{cs_org} = $org;
1326 $ctx->{cs_date} = $date;
1327 $ctx->{cs_time} = $time;
1328 $ctx->{cs_notes} = $notes;
1329 $ctx->{cs_slot_id} = $slot->id if ($slot);
1330 $ctx->{cs_slot} = $slot;
1332 if ($cs_action eq 'reset') {
1333 $ctx->{cs_org} = $org = undef;
1334 $ctx->{cs_date} = $date = undef;
1335 $ctx->{cs_time} = $time = undef;
1336 $ctx->{cs_notes} = $notes = undef;
1337 $ctx->{cs_slot_id} = $slot_id = undef;
1338 $ctx->{cs_slot} = $slot = undef;
1339 } elsif ($cs_action eq 'save' && $org && $date && $time) {
1340 my $mode = $slot ? 'update' : 'create';
1341 $slot = $circ->request(
1342 "open-ils.curbside.${mode}_appointment",
1343 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1346 if (defined $U->event_code($slot)) {
1347 $self->apache->log->warn(
1348 "error attempting to $mode a curbside appointment for patron ".
1349 $e->requestor->id . ", got event " . $slot->{textcode}
1351 $ctx->{curbside_action_event} = $slot;
1352 $ctx->{cs_slot} = undef;
1354 $ctx->{cs_slot} = $slot;
1356 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1357 } elsif ($cs_action eq 'cancel' && $slot) {
1358 my $curbsides = $U->simplereq(
1359 'open-ils.curbside',
1360 'open-ils.curbside.delete_appointment',
1361 $e->authtoken, $slot->id
1363 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1364 } elsif ($cs_action eq 'arrive' && $slot) {
1365 my $curbsides = $U->simplereq(
1366 'open-ils.curbside',
1367 'open-ils.curbside.mark_arrived',
1368 $e->authtoken, $slot->id
1370 } elsif ($cs_action eq 'deliver' && $slot) {
1371 my $curbsides = $U->simplereq(
1372 'open-ils.curbside',
1373 'open-ils.curbside.mark_delivered',
1374 $e->authtoken, $slot->id
1378 if ($date and $org and !$ctx->{cs_times}{$org}{$date}) {
1379 $ctx->{cs_times}{$org}{$date} = $circ->request(
1380 'open-ils.curbside.times_for_date.atomic',
1381 $e->authtoken, $date, $org
1387 return defined($url) ? $self->generic_redirect($url) : undef;
1390 sub load_myopac_holds {
1392 my $e = $self->editor;
1393 my $ctx = $self->ctx;
1395 my $limit = $self->cgi->param('limit') || 15;
1396 my $offset = $self->cgi->param('offset') || 0;
1397 my $action = $self->cgi->param('action') || '';
1398 my $hold_id = $self->cgi->param('hid');
1399 my $available = int($self->cgi->param('available') || 0);
1401 my $hold_handle_result;
1402 $hold_handle_result = $self->handle_hold_update($action) if $action;
1405 if ($self->cgi->param('sort') ne "") {
1406 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1409 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1412 if($holds_object->{holds}) {
1413 $ctx->{holds} = $holds_object->{holds};
1414 $ctx->{curbside_appointments} = {};
1416 $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1418 for my $cs (@{$holds_object->{curbsides}}) {
1420 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1421 $ctx->{cs_times}{$cs->org}{$dt} = $U->simplereq(
1422 'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1423 $e->authtoken, $dt, $cs->org
1426 $ctx->{curbside_appointments}{$cs->org} = $cs;
1429 $ctx->{holds_ids} = $holds_object->{all_ids};
1430 $ctx->{holds_limit} = $limit;
1431 $ctx->{holds_offset} = $offset;
1433 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1436 sub load_myopac_hold_subscriptions {
1438 my $e = $self->editor;
1439 my $ctx = $self->ctx;
1441 my $sub_remove = $self->cgi->param('remove');
1443 if ($sub_remove and $ctx->{user}->id) {
1444 my $sub_entries = $self->editor->search_container_user_bucket_item(
1445 { bucket => $sub_remove, target_user => $ctx->{user}->id }
1448 $self->editor->xact_begin;
1449 $self->editor->delete_container_user_bucket_item($_) for @$sub_entries;
1450 $self->editor->xact_commit;
1452 return $self->generic_redirect(
1453 $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/hold_subscriptions'
1457 return Apache2::Const::OK;
1462 sub load_place_hold {
1464 my $ctx = $self->ctx;
1465 my $gos = $ctx->{get_org_setting};
1466 my $e = $self->editor;
1467 my $cgi = $self->cgi;
1469 $self->ctx->{page} = 'place_hold';
1470 my @targets = uniq $cgi->param('hold_target');
1471 my @parts = $cgi->param('part');
1473 $ctx->{hold_subscription} = $cgi->param('hold_subscription');
1474 $ctx->{hold_type} = $cgi->param('hold_type');
1475 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1476 $ctx->{email_notify} = $cgi->param('email_notify');
1477 if ($cgi->param('phone_notify_checkbox')) {
1478 $ctx->{phone_notify} = $cgi->param('phone_notify');
1480 if ($cgi->param('sms_notify_checkbox')) {
1481 $ctx->{sms_notify} = $cgi->param('sms_notify');
1482 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1485 return $self->generic_redirect unless @targets;
1487 # Check for multiple hold placement via the num_copies widget.
1488 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1489 if ($num_copies > 1) {
1490 # Only if we have 1 hold target and no parts.
1491 if (scalar(@targets) == 1 && !$parts[0]) {
1492 # Also, only for M and T holds.
1493 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1494 # Add the extra holds to @targets. NOTE: We start with
1495 # 1 and go to < $num_copies to account for the
1497 for (my $i = 1; $i < $num_copies; $i++) {
1498 push(@targets, $targets[0]);
1504 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1506 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1511 au => ['settings', 'card']
1514 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1515 my $user_setting_map = {
1516 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1518 $ctx->{staff_recipient}->settings
1521 $ctx->{user_setting_map} = $user_setting_map;
1523 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1524 if ($default_notify =~ /email/) {
1525 $ctx->{default_email_notify} = 'checked';
1527 $ctx->{default_email_notify} = '';
1529 if ($default_notify =~ /phone/) {
1530 $ctx->{default_phone_notify} = 'checked';
1532 $ctx->{default_phone_notify} = '';
1534 if ($default_notify =~ /sms/) {
1535 $ctx->{default_sms_notify} = 'checked';
1537 $ctx->{default_sms_notify} = '';
1539 if ($cgi->param('hold_suspend')) {
1541 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1542 # We should use a date input type on the forms once it is supported by Firefox.
1543 # I didn't do that now because it is not available in a general release.
1544 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1546 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1547 $ctx->{thaw_date} = $dt->ymd;
1550 $logger->warn("ignoring invalid thaw_date when placing hold request");
1556 # If we have a default pickup location, grab it
1557 if ($$user_setting_map{'opac.default_pickup_location'}) {
1558 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1561 my $request_lib = $e->requestor->ws_ou;
1563 $ctx->{hold_data} = \@hold_data;
1565 $data_filler = sub {
1567 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1568 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1569 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1570 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1571 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1572 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1576 my $type_dispatch = {
1578 # target metarecords
1579 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1581 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1585 for my $id (@targets) {
1586 my ($mr) = grep {$_->id eq $id} @$mrecs;
1588 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1589 my $filter_data = $U->simplereq(
1591 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1593 my $holdable_formats =
1594 $self->compile_holdable_formats($mr->id);
1596 push(@hold_data, $data_filler->({
1598 record => $mr->master_record,
1599 holdable_formats => $holdable_formats,
1600 metarecord_filters => $filter_data->{metarecord}
1605 my $recs = $e->batch_retrieve_biblio_record_entry(
1606 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1610 for my $id (@targets) { # force back into the correct order
1611 my ($rec) = grep {$_->id eq $id} @$recs;
1613 # NOTE: if tpac ever supports locked-down pickup libs,
1614 # we'll need to pass a pickup_lib param along with the
1615 # record to filter the set of monographic parts.
1616 my $parts = $U->simplereq(
1618 'open-ils.search.biblio.record_hold_parts',
1619 {record => $rec->id}
1622 # T holds on records that have parts are OK, but if the record has
1623 # no non-part copies, the hold will ultimately fail. When that
1624 # happens, require the user to select a part.
1625 my $part_required = 0;
1627 my $np_copies = $e->json_query({
1628 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1629 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1631 '+acp' => {deleted => 'f'},
1632 '+acn' => {deleted => 'f', record => $rec->id},
1633 '+acpm' => {id => undef}
1636 $part_required = 1 if $np_copies->[0]->{count} == 0;
1639 push(@hold_data, $data_filler->({
1643 part_required => $part_required
1648 my $vols = $e->batch_retrieve_asset_call_number([
1651 "flesh_fields" => {"acn" => ["record"]}
1653 ], {substream => 1});
1655 for my $id (@targets) {
1656 my ($vol) = grep {$_->id eq $id} @$vols;
1657 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1661 my $copies = $e->batch_retrieve_asset_copy([
1665 "acn" => ["record"],
1666 "acp" => ["call_number"]
1669 ], {substream => 1});
1671 for my $id (@targets) {
1672 my ($copy) = grep {$_->id eq $id} @$copies;
1673 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1677 my $isses = $e->batch_retrieve_serial_issuance([
1681 "siss" => ["subscription"], "ssub" => ["record_entry"]
1684 ], {substream => 1});
1686 for my $id (@targets) {
1687 my ($iss) = grep {$_->id eq $id} @$isses;
1688 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1693 }->{$ctx->{hold_type}}->();
1695 # caller sent bad target IDs or the wrong hold type
1696 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1698 # generate the MARC xml for each record
1699 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1701 my $pickup_lib = $cgi->param('pickup_lib');
1702 # no pickup lib means no holds placement, except for subscriptions
1703 return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1705 $ctx->{hold_attempt_made} = 1;
1707 # Give the original CGI params back to the user in case they
1708 # want to try to override something.
1709 $ctx->{orig_params} = $cgi->Vars;
1710 delete $ctx->{orig_params}{submit};
1711 delete $ctx->{orig_params}{hold_target};
1712 delete $ctx->{orig_params}{part};
1714 my $usr = $e->requestor->id;
1716 if ($ctx->{is_staff}) {
1717 $logger->info("Staff initiated hold");
1718 if (!$cgi->param("hold_usr_is_requestor")) {
1719 # find the real hold target
1721 $usr = $U->simplereq(
1723 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1724 $e->authtoken, $cgi->param("hold_usr"));
1726 if (defined $U->event_code($usr)) {
1727 $ctx->{hold_failed} = 1;
1728 $ctx->{hold_failed_event} = $usr;
1732 if ($ctx->{hold_subscription}) {
1733 # this is a batch event, hold "user" is a bucket id
1734 $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1735 $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1739 # target_id is the true target_id for holds placement.
1740 # needed for attempt_hold_placement()
1741 # With the exception of P-type holds, target_id == target->id.
1742 $_->{target_id} = $_->{target}->id for @hold_data;
1744 if ($ctx->{hold_type} eq 'T') {
1746 # Much like quantum wave-particles, P-type holds pop into
1747 # and out of existence at the user's whim. For our purposes,
1748 # we treat such holds as T(itle) holds with a selected_part
1749 # designation. When the time comes to pass the hold information
1750 # off for holds possibility testing and placement, make it look
1751 # like a real P-type hold.
1752 my (@p_holds, @t_holds);
1754 # Now that we have the num_copies field for mutliple title and
1755 # metarecord hold placement, the number of holds and parts
1756 # arrays can get out of sync. We only want to parse out parts
1757 # if the numbers are equal.
1758 if ($#hold_data == $#parts) {
1759 for my $idx (0..$#parts) {
1760 my $hdata = $hold_data[$idx];
1761 if (my $part = $parts[$idx]) {
1762 $hdata->{target_id} = $part;
1763 $hdata->{selected_part} = $part;
1764 push(@p_holds, $hdata);
1766 push(@t_holds, $hdata);
1770 @t_holds = @hold_data;
1773 $self->apache->log->warn("$#parts : @t_holds");
1775 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1776 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1779 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1782 # NOTE: we are leaving the staff-placed patron barcode cookie
1783 # in place. Otherwise, it's not possible to place more than
1784 # one hold for the patron within a staff/patron session. This
1785 # does leave the barcode to linger longer than is ideal, but
1786 # normal staff work flow will cause the cookie to be replaced
1787 # with each new patron anyway.
1788 # TODO: See about getting the staff client to clear the cookie
1790 # return to the place_hold page so the results of the hold
1791 # placement attempt can be reported to the user
1792 return Apache2::Const::OK;
1795 sub attempt_hold_placement {
1796 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1797 my $cgi = $self->cgi;
1798 my $ctx = $self->ctx;
1799 my $e = $self->editor;
1801 my $user_container = undef;
1802 if (ref($usr)) { # $usr is actually a container for a subscription...
1803 $user_container = $usr->id;
1804 return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1807 # First see if we should warn/block for any holds that
1808 # might have locally available items for non-subscriptions.
1809 if (!$user_container) {
1810 for my $hdata (@hold_data) {
1811 my ($local_block, $local_alert) = $self->local_avail_concern(
1812 $hdata->{target_id}, $hold_type, $pickup_lib);
1815 $hdata->{hold_failed} = 1;
1816 $hdata->{hold_local_block} = 1;
1817 } elsif ($local_alert) {
1818 $hdata->{hold_failed} = 1;
1819 $hdata->{hold_local_alert} = 1;
1824 my $method = $user_container
1825 ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1826 : 'open-ils.circ.holds.test_and_create.batch';
1828 if ($cgi->param('override')) {
1829 $method .= '.override';
1831 } elsif (!$ctx->{is_staff}) {
1833 $method .= '.override' if $self->ctx->{get_org_setting}->(
1834 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1837 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1840 if(@create_targets) {
1842 # holdable formats may be different for each MR hold.
1843 # map each set to the ID of the target.
1844 my $holdable_formats = {};
1845 if ($hold_type eq 'M') {
1846 $holdable_formats->{$_->{target_id}} =
1847 $_->{holdable_formats} for @hold_data;
1850 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1852 my @create_params = ();
1854 if ($user_container) {
1857 hold_type => $hold_type,
1858 holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1867 pickup_lib => $pickup_lib,
1868 hold_type => $hold_type,
1869 holdable_formats_map => $holdable_formats,
1875 my $breq = $bses->request($method, $e->authtoken, @create_params);
1877 while (my $resp = $breq->recv) {
1879 $resp = $resp->content;
1880 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1882 if ($U->event_code($resp)) {
1883 $ctx->{general_hold_error} = $resp;
1887 # subscription batch create sends an initial response to assist with client-side counting
1890 defined($$resp{count}) and $$resp{count} == 0
1891 and defined($$resp{total}) and $$resp{total} > 0
1894 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1895 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1896 my $result = $resp->{result};
1898 if ($U->event_code($result)) {
1899 # e.g. permission denied
1900 $hdata->{hold_failed} = 1;
1901 $hdata->{hold_failed_event} = $result;
1905 if(not ref $result and $result > 0) {
1906 # successul hold returns the hold ID
1907 $hdata->{hold_success} = $result;
1910 # hold-specific failure event
1911 $hdata->{hold_failed} = 1;
1913 if (ref $result eq 'HASH') {
1914 $hdata->{hold_failed_event} = $result->{last_event};
1916 if ($result->{age_protected_copy}) {
1917 my %temp = %{$hdata->{hold_failed_event}};
1918 my $theTextcode = $temp{"textcode"};
1919 $theTextcode.=".override";
1920 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1921 $hdata->{age_protect} = 1;
1923 $hdata->{could_override} = $result->{place_unfillable} ||
1924 $self->test_could_override($hdata->{hold_failed_event});
1926 } elsif (ref $result eq 'ARRAY') {
1927 $hdata->{hold_failed_event} = $result->[0];
1929 if ($result->[3]) { # age_protect_only
1930 my %temp = %{$hdata->{hold_failed_event}};
1931 my $theTextcode = $temp{"textcode"};
1932 $theTextcode.=".override";
1933 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1934 $hdata->{age_protect} = 1;
1936 $hdata->{could_override} = $result->[4] || # place_unfillable
1937 $self->test_could_override($hdata->{hold_failed_event});
1947 if ($self->cgi->param('clear_cart')) {
1948 $self->clear_anon_cache;
1952 # pull the selected formats and languages for metarecord holds
1953 # from the CGI params and map them into the JSON holdable
1954 # formats...er, format.
1955 # if no metarecord is provided, we'll pull it from the target
1956 # of the provided hold.
1957 sub compile_holdable_formats {
1958 my ($self, $mr_id, $hold_id) = @_;
1959 my $e = $self->editor;
1960 my $cgi = $self->cgi;
1962 # exit early if not needed
1964 grep /metarecord_formats_|metarecord_langs_/,
1967 # CGI params are based on the MR id, since during hold placement
1968 # we have no old ID. During hold edit, map the hold ID back to
1969 # the metarecod target.
1971 $e->retrieve_action_hold_request($hold_id)->target
1974 my $format_attr = $self->ctx->{get_cgf}->(
1975 'opac.metarecord.holds.format_attr');
1977 if (!$format_attr) {
1978 $logger->error("Missing config.global_flag: ".
1979 "opac.metarecord.holds.format_attr!");
1983 $format_attr = $format_attr->value;
1985 # during hold placement or edit submission, the user selects
1986 # which of the available formats/langs are acceptable.
1987 # Capture those here as the holdable_formats for the MR hold.
1988 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1989 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1991 # map the selected attrs into the JSON holdable_formats structure
1993 if (@selected_formats) {
1995 map { {_attr => $format_attr, _val => $_} }
1999 if (@selected_langs) {
2001 map { {_attr => 'item_lang', _val => $_} }
2006 return OpenSRF::Utils::JSON->perl2JSON($blob);
2009 sub fetch_user_circs {
2011 my $flesh = shift; # flesh bib data, etc.
2012 my $circ_ids = shift;
2016 my $e = $self->editor;
2021 @circ_ids = @$circ_ids;
2026 select => {circ => ['id']},
2030 usr => $e->requestor->id,
2031 checkin_time => undef,
2033 {stop_fines => undef},
2034 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2038 order_by => {circ => ['due_date']}
2041 $query->{limit} = $limit if $limit;
2042 $query->{offset} = $offset if $offset;
2044 my $ids = $e->json_query($query);
2045 @circ_ids = map {$_->{id}} @$ids;
2048 return [] unless @circ_ids;
2053 circ => ['target_copy'],
2054 acp => ['call_number','parts'],
2055 acn => ['record','owning_lib','prefix','suffix']
2060 my $circs = $e->search_action_circulation(
2061 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2064 for my $circ (@$circs) {
2067 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2068 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2069 undef # pre-cat copy, use the dummy title/author instead
2074 # make sure the final list is in the correct order
2076 for my $id (@circ_ids) {
2079 (grep { $_->{circ}->id == $id } @circs)
2083 return \@sorted_circs;
2087 sub handle_circ_renew {
2090 my $ctx = $self->ctx;
2092 my @renew_ids = $self->cgi->param('circ');
2094 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2096 # TODO: fire off renewal calls in batches to speed things up
2098 for my $circ (@$circs) {
2100 my $evt = $U->simplereq(
2102 'open-ils.circ.renew',
2103 $self->editor->authtoken,
2105 patron_id => $self->editor->requestor->id,
2106 copy_id => $circ->{circ}->target_copy,
2111 # TODO return these, then insert them into the circ data
2112 # blob that is shoved into the template for each circ
2113 # so the template won't have to match them
2114 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2120 sub load_myopac_circs {
2122 my $e = $self->editor;
2123 my $ctx = $self->ctx;
2126 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2127 my $offset = $self->cgi->param('offset') || 0;
2128 my $action = $self->cgi->param('action') || '';
2130 # perform the renewal first if necessary
2131 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2133 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2135 my $success_renewals = 0;
2136 my $failed_renewals = 0;
2137 for my $data (@{$ctx->{circs}}) {
2138 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2141 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2143 # extract the fail_part, if present, from the event payload;
2144 # since # the payload is an acp object in some cases,
2145 # blindly looking for a # 'fail_part' key in the template can
2147 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2148 $evt->{payload}->{fail_part} :
2151 $data->{renewal_response} = $evt;
2152 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2153 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2157 $ctx->{success_renewals} = $success_renewals;
2158 $ctx->{failed_renewals} = $failed_renewals;
2160 return Apache2::Const::OK;
2163 sub load_myopac_circ_history {
2165 my $e = $self->editor;
2166 my $ctx = $self->ctx;
2167 my $limit = $self->cgi->param('limit') || 15;
2168 my $offset = $self->cgi->param('offset') || 0;
2169 my $action = $self->cgi->param('action') || '';
2171 my $circ_handle_result;
2172 $circ_handle_result = $self->handle_circ_update($action) if $action;
2174 $ctx->{circ_history_limit} = $limit;
2175 $ctx->{circ_history_offset} = $offset;
2177 # Defer limitation to circ_history.tt2 when sorting
2178 if ($self->cgi->param('sort')) {
2183 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2184 return Apache2::Const::OK;
2187 # if 'flesh' is set, copy data etc. is loaded and the return value is
2188 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2190 sub fetch_user_circ_history {
2191 my ($self, $flesh, $limit, $offset) = @_;
2192 my $e = $self->editor;
2195 $limits{offset} = $offset if defined $offset;
2196 $limits{limit} = $limit if defined $limit;
2201 auch => ['target_copy','source_circ'],
2202 acp => ['call_number','parts'],
2203 acn => ['record','prefix','suffix']
2208 my $circs = $e->search_action_user_circ_history(
2210 {usr => $e->requestor->id},
2211 { # order newest to oldest by default
2212 order_by => {auch => 'xact_start DESC'},
2213 $flesh ? %flesh_ops : (),
2221 return $circs unless $flesh;
2225 my %unapi_cache = ();
2226 for my $circ (@$circs) {
2227 if ($circ->target_copy->call_number->id == -1) {
2230 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2234 my $bre_id = $circ->target_copy->call_number->record->id;
2236 if (exists $unapi_cache{$bre_id}) {
2237 $unapi = $unapi_cache{$bre_id};
2239 my $result = $e->json_query({
2241 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2245 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2256 marc_xml => undef # failed, but try to go on
2265 sub handle_circ_update {
2268 my $circ_ids = shift;
2270 $circ_ids //= [$self->cgi->param('circ_id')];
2272 if ($action =~ /delete/) {
2274 circ_ids => $circ_ids,
2279 'open-ils.actor.history.circ.clear',
2280 $self->editor->authtoken,
2288 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2289 sub load_myopac_hold_history {
2291 my $e = $self->editor;
2292 my $ctx = $self->ctx;
2293 my $limit = $self->cgi->param('limit') || 15;
2294 my $offset = $self->cgi->param('offset') || 0;
2295 $ctx->{hold_history_limit} = $limit;
2296 $ctx->{hold_history_offset} = $offset;
2298 my $hold_ids = $e->json_query({
2302 transform => 'action.usr_visible_holds',
2303 result_field => 'id'
2307 where => {id => $e->requestor->id}
2310 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2311 if($holds_object->{holds}) {
2312 $ctx->{holds} = $holds_object->{holds};
2314 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2316 return Apache2::Const::OK;
2319 sub load_myopac_payment_form {
2322 my $e = $self->editor;
2324 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2326 if ( ! $self->cgi->param('last_chance') # only do this once
2327 && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')
2328 && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2329 my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2330 my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2331 my $stripe = Business::Stripe->new(-api_key => $skey);
2332 my $intent = $stripe->api('post', 'payment_intents',
2333 amount => $self->ctx->{fines}->{balance_owed} * 100,
2334 currency => $currency || 'usd'
2336 if ($stripe->success) {
2337 $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2339 $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2340 $self->ctx->{cc_configuration_error} = 1;
2344 if ($r) { return $r; }
2345 $r = $self->prepare_extended_user_info and return $r;
2347 return Apache2::Const::OK;
2350 # TODO: add other filter options as params/configs/etc.
2351 sub load_myopac_payments {
2353 my $limit = $self->cgi->param('limit') || 20;
2354 my $offset = $self->cgi->param('offset') || 0;
2355 my $e = $self->editor;
2357 $self->ctx->{payment_history_limit} = $limit;
2358 $self->ctx->{payment_history_offset} = $offset;
2361 $args->{limit} = $limit if $limit;
2362 $args->{offset} = $offset if $offset;
2364 if (my $max_age = $self->ctx->{get_org_setting}->(
2365 $e->requestor->home_ou, "opac.payment_history_age_limit"
2367 my $min_ts = DateTime->now(
2368 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2369 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2371 $logger->info("XXX min_ts: $min_ts");
2372 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2375 $self->ctx->{payments} = $U->simplereq(
2377 'open-ils.actor.user.payments.retrieve.atomic',
2378 $e->authtoken, $e->requestor->id, $args);
2380 return Apache2::Const::OK;
2383 # 1. caches the form parameters
2384 # 2. loads the credit card payment "Processing..." page
2385 sub load_myopac_pay_init {
2387 my $cache = OpenSRF::Utils::Cache->new('global');
2389 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2391 if (!@payment_xacts) {
2392 # for consistency with load_myopac_payment_form() and
2393 # to preserve backwards compatibility, if no xacts are
2394 # selected, assume all (applicable) transactions are wanted.
2395 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2396 return $stat if $stat;
2398 map { $_->{xact}->id } (
2399 @{$self->ctx->{fines}->{circulation}},
2400 @{$self->ctx->{fines}->{grocery}}
2404 return $self->generic_redirect unless @payment_xacts;
2406 my $cc_args = {"where_process" => 1};
2408 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2409 number cvv2 expire_year expire_month billing_first
2410 billing_last billing_address billing_city billing_state
2411 billing_zip stripe_payment_intent stripe_client_secret
2415 cc_args => $cc_args,
2416 user => $self->ctx->{user}->id,
2417 xacts => \@payment_xacts
2420 # generate a temporary cache token and cache the form data
2421 my $token = md5_hex($$ . time() . rand());
2422 $cache->put_cache($token, $cache_args, 30);
2424 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2426 # after we render the processing page, we quickly redirect to submit
2427 # the actual payment. The refresh url contains the payment token.
2428 # It also contains the list of xact IDs, which allows us to clear the
2429 # cache at the earliest possible time while leaving a trace of which
2430 # transactions we were processing, so the UI can bring the user back
2431 # to the payment form w/ the same xacts if the payment fails.
2433 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2434 $refresh .= ";xact=$_" for @payment_xacts;
2435 $self->ctx->{refresh} = $refresh;
2437 return Apache2::Const::OK;
2440 # retrieve the cached CC payment info and send off for processing
2441 sub load_myopac_pay {
2443 my $token = $self->ctx->{page_args}->[0];
2444 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2446 my $cache = OpenSRF::Utils::Cache->new('global');
2447 my $cache_args = $cache->get_cache($token);
2448 $cache->delete_cache($token);
2450 # this page is loaded immediately after the token is created.
2451 # if the cached data is not there, it's because of an invalid
2452 # token (or cache failure) and not because of a timeout.
2453 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2455 my @payment_xacts = @{$cache_args->{xacts}};
2456 my $cc_args = $cache_args->{cc_args};
2458 # as an added security check, verify the user submitting
2459 # the form is the same as the user whose data was cached
2460 return Apache2::Const::HTTP_BAD_REQUEST unless
2461 $cache_args->{user} == $self->ctx->{user}->id;
2463 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2466 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2468 # balance_owed is computed specifically from the fines we're paying
2469 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2470 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2471 return Apache2::Const::HTTP_BAD_REQUEST;
2475 "cc_args" => $cc_args,
2476 "userid" => $self->ctx->{user}->id,
2477 "payment_type" => "credit_card_payment",
2478 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2481 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2482 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2485 $self->ctx->{"payment_response"} = $resp;
2487 unless ($resp->{"textcode"}) {
2488 $self->ctx->{printable_receipt} = $U->simplereq(
2489 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2490 $self->editor->authtoken, $resp->{payments}
2494 return Apache2::Const::OK;
2497 sub load_myopac_receipt_print {
2500 $self->ctx->{printable_receipt} = $U->simplereq(
2501 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2502 $self->editor->authtoken, [$self->cgi->param("payment")]
2505 return Apache2::Const::OK;
2508 sub load_myopac_receipt_email {
2511 # The following ML method doesn't actually check whether the user in
2512 # question has an email address, so we do.
2513 if ($self->ctx->{user}->email) {
2514 $self->ctx->{email_receipt_result} = $U->simplereq(
2515 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2516 $self->editor->authtoken, [$self->cgi->param("payment")]
2519 $self->ctx->{email_receipt_result} =
2520 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2523 return Apache2::Const::OK;
2527 my ($self, $limit, $offset, $id_list) = @_;
2529 # XXX TODO: check for failure after various network calls
2531 # It may be unclear, but this result structure lumps circulation and
2532 # reservation fines together, and keeps grocery fines separate.
2533 $self->ctx->{"fines"} = {
2534 "circulation" => [],
2541 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2543 # TODO: This should really be a ML call, but the existing calls
2544 # return an excessive amount of data and don't offer streaming
2546 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2548 my $req = $cstore->request(
2549 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2551 usr => $self->editor->requestor->id,
2552 balance_owed => {'!=' => 0},
2553 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2558 mobts => [qw/grocery circulation reservation/],
2559 bresv => ['target_resource_type'],
2563 circ => ['target_copy'],
2564 acp => ['call_number'],
2567 order_by => { mobts => 'xact_start' },
2572 # Collect $$ amounts from each transaction for summing below.
2573 my (@paid_amounts, @owed_amounts, @balance_amounts);
2575 while(my $resp = $req->recv) {
2576 my $mobts = $resp->content;
2577 my $circ = $mobts->circulation;
2580 if($mobts->grocery) {
2581 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2582 $last_billing = pop(@billings);
2585 push(@paid_amounts, $mobts->total_paid);
2586 push(@owed_amounts, $mobts->total_owed);
2587 push(@balance_amounts, $mobts->balance_owed);
2589 my $marc_xml = undef;
2590 if ($mobts->xact_type eq 'reservation' and
2591 $mobts->reservation->target_resource_type->record) {
2592 $marc_xml = XML::LibXML->new->parse_string(
2593 $mobts->reservation->target_resource_type->record->marc
2595 } elsif ($mobts->xact_type eq 'circulation' and
2596 $circ->target_copy->call_number->id != -1) {
2597 $marc_xml = XML::LibXML->new->parse_string(
2598 $circ->target_copy->call_number->record->marc
2603 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2606 last_grocery_billing => $last_billing,
2607 marc_xml => $marc_xml
2614 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2615 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2616 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2621 sub prepare_fines_for_payment {
2622 # This assumes $self->prepare_fines has already been run
2626 if ($self->ctx->{fines}) {
2627 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2628 @{$self->ctx->{fines}->{circulation}},
2629 @{$self->ctx->{fines}->{grocery}}
2636 sub load_myopac_main {
2638 my $limit = $self->cgi->param('limit') || 0;
2639 my $offset = $self->cgi->param('offset') || 0;
2640 $self->ctx->{search_ou} = $self->_get_search_lib();
2641 $self->ctx->{user}->notes(
2642 $self->editor->search_actor_usr_message({
2643 usr => $self->ctx->{user}->id,
2647 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2650 sub load_myopac_update_email {
2652 my $e = $self->editor;
2653 my $ctx = $self->ctx;
2654 my $email = $self->cgi->param('email') || '';
2655 my $current_pw = $self->cgi->param('current_pw') || '';
2657 # needed for most up-to-date email address
2658 if (my $r = $self->prepare_extended_user_info) { return $r };
2660 return Apache2::Const::OK
2661 unless $self->cgi->request_method eq 'POST';
2663 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2664 $ctx->{invalid_email} = $email;
2665 return Apache2::Const::OK;
2668 my $stat = $U->simplereq(
2670 'open-ils.actor.user.email.update',
2671 $e->authtoken, $email, $current_pw);
2673 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2674 $ctx->{password_incorrect} = 1;
2675 return Apache2::Const::OK;
2678 unless ($self->cgi->param("redirect_to")) {
2679 my $url = $self->apache->unparsed_uri;
2680 $url =~ s/update_email/prefs/;
2682 return $self->generic_redirect($url);
2685 return $self->generic_redirect;
2688 sub load_myopac_update_username {
2690 my $e = $self->editor;
2691 my $ctx = $self->ctx;
2692 my $username = $self->cgi->param('username') || '';
2693 my $current_pw = $self->cgi->param('current_pw') || '';
2695 $self->prepare_extended_user_info;
2697 my $allow_change = 1;
2699 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2700 if(defined($lock_usernames) and $lock_usernames == 1) {
2701 # Policy says no username changes
2704 # We want this further down.
2705 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2706 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2707 if(!$username_unlimit) {
2709 # Default is "starts with a number"
2710 $regex_check = '^\d+';
2712 # You already have a username?
2713 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2718 if(!$allow_change) {
2719 my $url = $self->apache->unparsed_uri;
2720 $url =~ s/update_username/prefs/;
2722 return $self->generic_redirect($url);
2725 return Apache2::Const::OK
2726 unless $self->cgi->request_method eq 'POST';
2728 unless($username and $username !~ /\s/) { # any other username restrictions?
2729 $ctx->{invalid_username} = $username;
2730 return Apache2::Const::OK;
2733 # New username can't look like a barcode if we have a barcode regex
2734 if($regex_check and $username =~ /$regex_check/) {
2735 $ctx->{invalid_username} = $username;
2736 return Apache2::Const::OK;
2739 # New username has to look like a username if we have a username regex
2740 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2741 if($regex_check and $username !~ /$regex_check/) {
2742 $ctx->{invalid_username} = $username;
2743 return Apache2::Const::OK;
2746 if($username ne $e->requestor->usrname) {
2748 my $evt = $U->simplereq(
2750 'open-ils.actor.user.username.update',
2751 $e->authtoken, $username, $current_pw);
2753 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2754 $ctx->{password_incorrect} = 1;
2755 return Apache2::Const::OK;
2758 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2759 $ctx->{username_exists} = $username;
2760 return Apache2::Const::OK;
2764 my $url = $self->apache->unparsed_uri;
2765 $url =~ s/update_username/prefs/;
2767 return $self->generic_redirect($url);
2770 sub load_myopac_update_locale {
2772 my $e = $self->editor;
2773 my $ctx = $self->ctx;
2774 my $lang = $self->cgi->param('pref_lang') || '';
2775 my $current_pw = $self->cgi->param('current_pw') || '';
2777 $self->prepare_extended_user_info;
2779 my $locs = $U->simplereq(
2781 "open-ils.cstore.direct.config.i18n_locale.search.atomic",
2782 { "code" => { "!=" => undef } }
2786 foreach my $l (@$locs) { $user_locales{$l->code} = $l->name; }
2787 $self->ctx->{i18n_locales} = \%user_locales;
2789 return Apache2::Const::OK
2790 unless $self->cgi->request_method eq 'POST';
2792 if($lang ne $e->requestor->locale) {
2793 my $evt = $U->simplereq(
2795 'open-ils.actor.user.locale.update',
2796 $e->authtoken, $lang, $current_pw);
2798 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2799 $ctx->{password_incorrect} = 1;
2800 return Apache2::Const::OK;
2804 my $url = $self->apache->unparsed_uri;
2805 $url =~ s/update_locale/prefs/;
2807 return $self->generic_redirect($url);
2810 sub load_myopac_update_password {
2812 my $e = $self->editor;
2813 my $ctx = $self->ctx;
2815 return Apache2::Const::OK
2816 unless $self->cgi->request_method eq 'POST';
2818 my $current_pw = $self->cgi->param('current_pw') || '';
2819 my $new_pw = $self->cgi->param('new_pw') || '';
2820 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2822 unless($new_pw eq $new_pw2) {
2823 $ctx->{password_nomatch} = 1;
2824 return Apache2::Const::OK;
2827 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2830 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2831 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2834 if($pw_regex and $new_pw !~ /$pw_regex/) {
2835 $ctx->{password_invalid} = 1;
2836 return Apache2::Const::OK;
2839 my $evt = $U->simplereq(
2841 'open-ils.actor.user.password.update',
2842 $e->authtoken, $new_pw, $current_pw);
2845 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2846 $ctx->{password_incorrect} = 1;
2847 return Apache2::Const::OK;
2850 my $url = $self->apache->unparsed_uri;
2851 $url =~ s/update_password/prefs/;
2853 return $self->generic_redirect($url);
2856 sub _update_bookbag_metadata {
2857 my ($self, $bookbag) = @_;
2859 $bookbag->name($self->cgi->param("name"));
2860 $bookbag->description($self->cgi->param("description"));
2862 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2866 sub _get_lists_per_page {
2869 if($self->editor->requestor) {
2870 $self->timelog("Checking for opac.lists_per_page preference");
2871 # See if the user has a lists per page preference
2872 my $ipp = $self->editor->search_actor_user_setting({
2873 usr => $self->editor->requestor->id,
2874 name => 'opac.lists_per_page'
2876 $self->timelog("Got opac.lists_per_page preference");
2877 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2879 return 10; # default
2882 sub _get_items_per_page {
2885 if($self->editor->requestor) {
2886 $self->timelog("Checking for opac.list_items_per_page preference");
2887 # See if the user has a list items per page preference
2888 my $ipp = $self->editor->search_actor_user_setting({
2889 usr => $self->editor->requestor->id,
2890 name => 'opac.list_items_per_page'
2892 $self->timelog("Got opac.list_items_per_page preference");
2893 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2895 return 10; # default
2898 sub load_myopac_bookbags {
2900 my $e = $self->editor;
2901 my $ctx = $self->ctx;
2902 my $limit = $self->_get_lists_per_page || 10;
2903 my $offset = $self->cgi->param('offset') || 0;
2905 $ctx->{bookbags_limit} = $limit;
2906 $ctx->{bookbags_offset} = $offset;
2908 # for list item pagination
2909 my $item_limit = $self->_get_items_per_page;
2910 my $item_page = $self->cgi->param('item_page') || 1;
2911 my $item_offset = ($item_page - 1) * $item_limit;
2912 $ctx->{bookbags_item_page} = $item_page;
2914 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2915 $e->xact_begin; # replication...
2917 my $rv = $self->load_mylist;
2918 unless($rv eq Apache2::Const::OK) {
2923 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2925 {owner => $e->requestor->id, btype => 'bookbag'}, {
2926 order_by => {cbreb => 'name'},
2934 if(!$ctx->{bookbags}) {
2936 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2939 # We load the user prefs to get their default bookbag.
2940 $self->_load_user_with_prefs;
2942 # We also want a total count of the user's bookbags.
2944 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2946 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2948 my $r = $e->json_query($q);
2949 $ctx->{bookbag_count} = $r->[0]->{'count'};
2951 # If the user wants a specific bookbag's items, load them.
2953 if ($self->cgi->param("bbid")) {
2955 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2958 my $query = $self->_prepare_bookbag_container_query(
2959 $bookbag->id, $sorter, $modifier
2962 # Calculate total count of the items in selected bookbag.
2963 # This total includes record entries that have no assets available.
2964 my $bb_search_results = $U->simplereq(
2965 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2966 {"limit" => 1, "offset" => 0}, $query
2967 ); # we only need the count, so do the actual search with limit=1
2969 if ($bb_search_results) {
2970 $ctx->{bb_item_count} = $bb_search_results->{count};
2972 $logger->warn("search failed in load_myopac_bookbags()");
2973 $ctx->{bb_item_count} = 0; # fallback value
2976 #calculate page count
2977 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2979 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2980 if (!$self->_update_bookbag_metadata($bookbag)) {
2982 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2985 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2988 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2989 if ($self->cgi->param($param)) {
2990 my @vals = $self->cgi->param($param);
2991 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2995 return $self->generic_redirect($url);
2999 # we're done with our CStoreEditor. Rollback here so
3000 # later calls don't cause a timeout, resulting in a
3001 # transaction rollback under the covers.
3005 # For list items pagination
3007 "limit" => $item_limit,
3008 "offset" => $item_offset
3011 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
3012 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3014 # capture pref_ou for callnumber filter/display
3015 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
3017 # search for local callnumbers for display
3018 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
3020 my (undef, @recs) = $self->get_records_and_facets(
3021 [ map {$_->target_biblio_record_entry->id} @$items ],
3024 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
3026 site => $ctx->{get_aou}->($focus_ou)->shortname,
3027 pref_lib => $ctx->{pref_ou}
3031 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
3033 $bookbag->items($items);
3037 # If we have add_rec, we got here from the "Add to new list"
3038 # or "See all" popmenu items.
3039 if (my $add_rec = $self->cgi->param('add_rec')) {
3040 $self->ctx->{add_rec} = $add_rec;
3041 # But not in the staff client, 'cause that breaks things.
3042 unless ($self->ctx->{is_staff}) {
3043 # allow caller to provide the where_from in cases where
3044 # the referer is an intermediate error page
3045 if ($self->cgi->param('where_from')) {
3046 $self->ctx->{where_from} = $self->cgi->param('where_from');
3048 $self->ctx->{where_from} = $self->ctx->{referer};
3049 if ( my $anchor = $self->cgi->param('anchor') ) {
3050 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3056 # this rollback may be a dupe, but that's OK because
3057 # cstoreditor ignores dupe rollbacks
3060 return Apache2::Const::OK;
3064 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3065 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3066 sub load_myopac_bookbag_update {
3067 my ($self, $action, $list_id, @hold_recs) = @_;
3068 my $e = $self->editor;
3069 my $cgi = $self->cgi;
3071 # save_notes is effectively another action, but is passed in a separate
3072 # CGI parameter for what are really just layout reasons.
3073 $action = 'save_notes' if $cgi->param('save_notes');
3074 $action ||= $cgi->param('action');
3076 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3078 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3079 my @selected_item = $cgi->param('selected_item');
3080 my $shared = $cgi->param('shared');
3081 my $move_cart = $cgi->param('move_cart');
3082 my $name = $cgi->param('name');
3083 my $description = $cgi->param('description');
3087 # bail out if user is attempting an action that requires
3088 # that at least one list item be selected
3089 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3090 ($action eq 'place_hold' || $action eq 'print' ||
3091 $action eq 'email' || $action eq 'del_item')) {
3092 my $url = $self->ctx->{referer};
3093 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3094 return $self->generic_redirect($url);
3097 # This url intentionally leaves off the edit_notes parameter, but
3098 # may need to add some back in for paging.
3100 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3101 $self->ctx->{opac_root} . "/myopac/lists?";
3103 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3104 if ($cgi->param($param)) {
3105 my @vals = $cgi->param($param);
3106 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3110 if ($action eq 'create') {
3113 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3115 $list->description($description);
3116 $list->owner($e->requestor->id);
3117 $list->btype('bookbag');
3118 $list->pub($shared ? 't' : 'f');
3119 $success = $U->simplereq('open-ils.actor',
3120 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3121 if (ref($success) ne 'HASH') {
3122 $list_id = (ref($success)) ? $success->id : $success;
3123 if (scalar @add_rec) {
3124 foreach my $add_rec (@add_rec) {
3125 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3126 $item->bucket($list_id);
3127 $item->target_biblio_record_entry($add_rec);
3128 $success = $U->simplereq('open-ils.actor',
3129 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3130 last unless $success;
3134 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3135 foreach my $add_rec (@$list) {
3136 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3137 $item->bucket($list_id);
3138 $item->target_biblio_record_entry($add_rec);
3139 $success = $U->simplereq('open-ils.actor',
3140 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3141 last unless $success;
3143 $self->clear_anon_cache;
3146 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3149 $self->ctx->{bucket_failure_noname} = 1;
3152 } elsif($action eq 'place_hold') {
3154 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3155 my $from_basket = scalar(@hold_recs);
3156 unless (@hold_recs) {
3157 if (@selected_item) {
3158 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3159 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3163 return Apache2::Const::OK unless @hold_recs;
3164 $logger->info("placing holds from list page on: @hold_recs");
3166 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3167 $url .= ';hold_target=' . $_ for @hold_recs;
3168 $url .= ';from_basket=1' if $from_basket;
3169 foreach my $param (('loc', 'qtype', 'query')) {
3170 if ($cgi->param($param)) {
3171 my @vals = $cgi->param($param);
3172 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3175 return $self->generic_redirect($url);
3177 } elsif ($action eq 'print') {
3178 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3179 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3180 if (!$incoming_sort) {
3181 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3183 if (!$incoming_sort) {
3184 $incoming_sort = 'author';
3187 $incoming_sort =~ s/sort.*$//;
3189 $self->ctx->{sort} = $incoming_sort;
3190 $self->ctx->{sort_dir} = $sort_dir;
3192 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3193 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3194 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3195 return $self->load_mylist_print($temp_cache_key);
3196 } elsif ($action eq 'email') {
3197 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3198 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3199 if (!$incoming_sort) {
3200 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3202 if (!$incoming_sort) {
3203 $incoming_sort = 'author';
3206 $incoming_sort =~ s/sort.*$//;
3208 $self->ctx->{sort} = $incoming_sort;
3209 $self->ctx->{sort_dir} = $sort_dir;
3211 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3212 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3213 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3214 return $self->load_mylist_email($temp_cache_key);
3217 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3219 return Apache2::Const::HTTP_BAD_REQUEST unless
3220 $list and $list->owner == $e->requestor->id;
3223 if($action eq 'delete') {
3224 $success = $U->simplereq('open-ils.actor',
3225 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3227 # We check to see if we're deleting the user's default list.
3228 $self->_load_user_with_prefs;
3229 my $settings_map = $self->ctx->{user_setting_map};
3230 if ($$settings_map{'opac.default_list'} == $list_id) {
3231 # We unset the user's opac.default_list setting.
3232 $success = $U->simplereq(
3234 'open-ils.actor.patron.settings.update',
3237 { 'opac.default_list' => 0 }
3241 } elsif($action eq 'show') {
3242 unless($U->is_true($list->pub)) {
3244 $success = $U->simplereq('open-ils.actor',
3245 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3248 } elsif($action eq 'hide') {
3249 if($U->is_true($list->pub)) {
3251 $success = $U->simplereq('open-ils.actor',
3252 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3255 } elsif($action eq 'rename') {
3258 $success = $U->simplereq('open-ils.actor',
3259 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3262 } elsif($action eq 'add_rec') {
3263 foreach my $add_rec (@add_rec) {
3264 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3265 $item->bucket($list_id);
3266 $item->target_biblio_record_entry($add_rec);
3267 $success = $U->simplereq('open-ils.actor',
3268 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3269 last unless $success;
3271 # Redirect back where we came from if we have an anchor parameter:
3272 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3273 $url = $self->ctx->{referer};
3274 $url =~ s/#.*|$/#$anchor/;
3275 } elsif ($cgi->param('where_from')) {
3276 # Or, if we have a "where_from" parameter.
3277 $url = $cgi->param('where_from');
3279 } elsif ($action eq 'del_item') {
3280 foreach (@selected_item) {
3281 $success = $U->simplereq(
3283 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3285 last unless $success;
3287 } elsif ($action eq 'save_notes') {
3288 $success = $self->update_bookbag_item_notes;
3289 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3290 } elsif ($action eq 'make_default') {
3291 $success = $U->simplereq(
3293 'open-ils.actor.patron.settings.update',
3296 { 'opac.default_list' => $list_id }
3298 } elsif ($action eq 'remove_default') {
3299 $success = $U->simplereq(
3301 'open-ils.actor.patron.settings.update',
3304 { 'opac.default_list' => 0 }
3308 return $self->generic_redirect($url) if $success;
3310 $self->ctx->{where_from} = $cgi->param('where_from');
3311 $self->ctx->{bucket_action} = $action;
3312 $self->ctx->{bucket_action_failed} = 1;
3313 return Apache2::Const::OK;
3316 sub update_bookbag_item_notes {
3318 my $e = $self->editor;
3320 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3321 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3323 # We're going to leverage an API call that's already been written to check
3324 # permissions appropriately.
3326 my $a = create OpenSRF::AppSession("open-ils.actor");
3327 my $method = "open-ils.actor.container.item_note.cud";
3329 for my $note_key (@note_keys) {
3332 my $id = ($note_key =~ /(\d+)/)[0];
3335 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3336 my $event = $e->die_event;
3337 $self->apache->log->warn(
3338 "error retrieving cbrebin id $id, got event " .
3342 $self->ctx->{bucket_action_event} = $event;
3346 if (length($self->cgi->param($note_key))) {
3347 $note->ischanged(1);
3348 $note->note($self->cgi->param($note_key));
3350 $note->isdeleted(1);
3353 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3355 if (defined $U->event_code($r)) {
3356 $self->apache->log->warn(
3357 "attempt to modify cbrebin " . $note->id .
3358 " returned event " . $r->{textcode}
3362 $self->ctx->{bucket_action_event} = $r;
3367 for my $item_key (@item_keys) {
3368 my $id = int(($item_key =~ /(\d+)/)[0]);
3369 my $text = $self->cgi->param($item_key);
3372 next unless length $text;
3374 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3379 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3381 if (defined $U->event_code($r)) {
3382 $self->apache->log->warn(
3383 "attempt to create cbrebin for item " . $note->item .
3384 " returned event " . $r->{textcode}
3388 $self->ctx->{bucket_action_event} = $r;
3397 sub load_myopac_bookbag_print {
3400 my $id = int($self->cgi->param("list"));
3402 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3405 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3409 # Get the bookbag object itself, assuming we're allowed to.
3410 if ($self->editor->allowed("VIEW_CONTAINER")) {
3412 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3414 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3418 "owner" => $self->editor->requestor->id,
3422 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3424 $bbag = pop @$bookbags;
3427 # If we have a bookbag we're allowed to look at, issue the A/T event
3428 # to get CSV, passing as a user param that search query we built before.
3430 $self->ctx->{csv} = $U->fire_object_event(
3431 undef, "container.biblio_record_entry_bucket.csv",
3432 $bbag, $self->editor->requestor->home_ou,
3433 undef, {"item_search" => $item_search}
3437 # Create a reasonable filename and set the content disposition to
3438 # provoke browser download dialogs.
3439 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3441 return $self->set_file_download_headers("$filename.csv");
3444 sub load_myopac_circ_history_export {
3446 my $e = $self->editor;
3447 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3449 my $circs = $self->fetch_user_circ_history(1);
3451 $self->ctx->{csv}->{circs} = $circs;
3452 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3456 sub load_myopac_reservations {
3458 my $e = $self->editor;
3459 my $ctx = $self->ctx;
3461 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3462 $e->authtoken, undef
3465 $ctx->{reservations} = $upcoming;
3466 return Apache2::Const::OK;
3470 sub load_password_reset {
3472 my $cgi = $self->cgi;
3473 my $ctx = $self->ctx;
3474 my $barcode = $cgi->param('barcode');
3475 my $username = $cgi->param('username');
3476 my $email = $cgi->param('email');
3477 my $pwd1 = $cgi->param('pwd1');
3478 my $pwd2 = $cgi->param('pwd2');
3479 my $uuid = $ctx->{page_args}->[0];
3483 $logger->info("patron password reset with uuid $uuid");
3485 if ($pwd1 and $pwd2) {
3487 if ($pwd1 eq $pwd2) {
3489 my $response = $U->simplereq(
3491 'open-ils.actor.patron.password_reset.commit',
3494 $logger->info("patron password reset response " . Dumper($response));
3496 if ($U->event_code($response)) { # non-success event
3498 my $code = $response->{textcode};
3500 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3501 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3504 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3505 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3510 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3513 } else { # passwords not equal
3515 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3518 } else { # 2 password values needed
3520 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3523 } elsif ($barcode or $username) {
3525 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3526 push(@params, $email) if $email;
3530 'open-ils.actor.patron.password_reset.request', @params);
3532 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3535 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3536 return Apache2::Const::OK;