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 use HTTP::Request::Common qw(POST GET);
25 sub prepare_extended_user_info {
28 my $e = $self->editor;
30 # are we already in a transaction?
31 my $local_xact = !$e->{xact_id};
32 $e->xact_begin if $local_xact;
34 # keep the original user object so we can restore
35 # login-specific data (e.g. workstation)
36 my $usr = $self->ctx->{user};
38 $self->ctx->{user} = $self->editor->retrieve_actor_user([
39 $self->ctx->{user}->id,
43 au => [qw/card home_ou addresses ident_type locale billing_address waiver_entries stat_cat_entries/, @extra_flesh],
44 "aou" => ["billing_address"],
45 "actscecm" => ["stat_cat"]
50 $e->rollback if $local_xact;
52 $self->ctx->{user}->wsid($usr->wsid);
53 $self->ctx->{user}->ws_ou($usr->ws_ou);
55 # discard replaced (negative-id) addresses.
56 $self->ctx->{user}->addresses([
57 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
59 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
60 unless $self->ctx->{user};
65 # Given an event returned by a failed attempt to create a hold, do we have
66 # permission to override? XXX Should the permission check be scoped to a
67 # given org_unit context?
68 sub test_could_override {
69 my ($self, $event) = @_;
71 return 0 unless $event;
72 return 1 if $self->editor->allowed($event->{textcode} . ".override");
73 return 1 if $event->{"fail_part"} and
74 $self->editor->allowed($event->{"fail_part"} . ".override");
78 # Find out whether we care that local copies are available
79 sub local_avail_concern {
80 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
82 my $would_block = $self->ctx->{get_org_setting}->
83 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
85 $self->ctx->{get_org_setting}->
86 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
87 not $self->cgi->param("override")
88 ) unless $would_block;
90 if ($would_block or $would_alert) {
92 "hold_target" => $hold_target,
93 "hold_type" => $hold_type,
94 "org_unit" => $pickup_lib
96 my $local_avail = $U->simplereq(
98 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
101 "copy availability information for " . Dumper($args) .
102 " is " . Dumper($local_avail)
104 if (%$local_avail) { # if hash not empty
105 $self->ctx->{hold_copy_available} = $local_avail;
106 return ($would_block, $would_alert);
114 # user : au object, fleshed
115 sub load_myopac_prefs {
117 my $cgi = $self->cgi;
118 my $e = $self->editor;
119 my $pending_addr = $cgi->param('pending_addr');
120 my $replace_addr = $cgi->param('replace_addr');
121 my $delete_pending = $cgi->param('delete_pending');
123 $self->prepare_extended_user_info;
124 my $user = $self->ctx->{user};
126 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
127 if(defined($lock_usernames) and $lock_usernames == 1) {
128 # Policy says no username changes
129 $self->ctx->{username_change_disallowed} = 1;
131 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
132 if(!$username_unlimit) {
133 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
135 # Default is "starts with a number"
136 $regex_check = '^\d+';
138 # You already have a username?
139 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
140 $self->ctx->{username_change_disallowed} = 1;
145 return Apache2::Const::OK unless
146 $pending_addr or $replace_addr or $delete_pending;
148 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
151 if( $pending_addr ) { # update an existing pending address
153 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
154 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
155 $paddr->$_( $cgi->param($_) ) for @form_fields;
157 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
159 $paddr = Fieldmapper::actor::user_address->new;
161 $paddr->usr($user->id);
162 $paddr->pending('t');
163 $paddr->replaces($replace_addr);
164 $paddr->$_( $cgi->param($_) ) for @form_fields;
166 } elsif( $delete_pending ) {
167 $paddr = $e->retrieve_actor_user_address($delete_pending);
168 return Apache2::Const::HTTP_BAD_REQUEST unless
169 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
170 $paddr->isdeleted(1);
173 my $resp = $U->simplereq(
175 'open-ils.actor.user.address.pending.cud',
176 $e->authtoken, $paddr);
178 if( $U->event_code($resp) ) {
179 $logger->error("Error updating pending address: $resp");
180 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
183 # in light of these changes, re-fetch latest data
185 $self->prepare_extended_user_info;
188 return Apache2::Const::OK;
191 sub load_myopac_prefs_notify {
193 my $e = $self->editor;
196 my $stat = $self->_load_user_with_prefs;
197 return $stat if $stat;
199 my $user_prefs = $self->fetch_optin_prefs;
200 $user_prefs = $self->update_optin_prefs($user_prefs)
201 if $self->cgi->request_method eq 'POST';
203 $self->ctx->{opt_in_settings} = $user_prefs;
205 return Apache2::Const::OK
206 unless $self->cgi->request_method eq 'POST';
209 my $set_map = $self->ctx->{user_setting_map};
213 opac.default_sms_notify
215 my $val = $self->cgi->param($key);
216 $settings{$key}= $val unless $$set_map{$key} eq $val;
219 my $key = 'opac.default_sms_carrier';
220 my $val = $self->cgi->param('sms_carrier');
221 $settings{$key}= $val unless $$set_map{$key} eq $val;
223 $key = 'opac.hold_notify';
224 my @notify_methods = ();
225 if ($self->cgi->param($key . ".email") eq 'on') {
226 push @notify_methods, "email";
228 if ($self->cgi->param($key . ".phone") eq 'on') {
229 push @notify_methods, "phone";
231 if ($self->cgi->param($key . ".sms") eq 'on') {
232 push @notify_methods, "sms";
234 $val = join("|",@notify_methods);
235 $settings{$key}= $val unless $$set_map{$key} eq $val;
237 # Send the modified settings off to be saved
240 'open-ils.actor.patron.settings.update',
241 $self->editor->authtoken, undef, \%settings);
243 # re-fetch user prefs
244 $self->ctx->{updated_user_settings} = \%settings;
246 # update holds: check if any changes affect any holds
247 my @llchgs = $self->_parse_prefs_notify_hold_related();
250 if ( $self->cgi->param('hasHoldsChanges') ) {
251 # propagate pref_notify changes to holds
252 for my $chset (@llchgs){
253 # FIXME is this still needed?
258 my $holds = $U->simplereq('open-ils.circ', 'open-ils.circ.holds.retrieve.by_usr.with_notify',
259 $e->authtoken, $e->requestor->id);
263 my $default_phone_changes = {};
264 my $sms_changes = {};
268 for my $chset (@llchgs) {
269 next if scalar(@$chset) < 3;
270 my ($old, $new, $field) = @$chset;
272 my $bool = $field =~ /_notify/ ? 1 : 0;
274 # find holds that would change
276 foreach my $hold (@$holds) {
277 if ($field eq 'email_notify') {
278 my $curr = $hold->{$field} eq 't' ? 'true' : 'false';
279 push @$affected, $hold if $curr ne $new;
280 } elsif ($field eq 'default_phone') {
281 my $old_phone = $hold->{phone_notify} // '';
282 $new_phone = $new // '';
283 push @{ $default_phone_changes->{ $old_phone } }, $hold->{id}
284 if $old_phone ne $new_phone;
285 } elsif ($field eq 'phone_notify') {
286 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
287 push @$affected, $hold if $curr ne $new;
288 } elsif ($field eq 'sms_notify') {
289 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
290 push @$affected, $hold if $curr ne $new;
291 } elsif ($field eq 'sms_info') {
292 my $old_carrier = $hold->{'sms_carrier'} // '';
293 my $old_sms = $hold->{'sms_notify'} // '';
294 $new_carrier = $new->{carrier} // '';
295 $new_sms = $new->{sms} // '';
296 if (!($old_carrier eq $new_carrier && $old_sms eq $new_sms)) {
297 push @{ $sms_changes->{ join("\t", $old_carrier, $old_sms) } }, $hold->{id};
302 # append affected array to chset
303 if (scalar(@$affected) > 0){
304 push(@$chset, [ map { $_->{id} } @$affected ]);
305 push(@ffectedChgs, $chset);
310 foreach my $old_phone (keys %$default_phone_changes) {
311 push(@ffectedChgs, [ $old_phone, $new_phone, 'default_phone', $default_phone_changes->{$old_phone} ]);
313 foreach my $old_sms_info (keys %$sms_changes) {
314 my ($old_carrier, $old_sms) = split /\t/, $old_sms_info;
316 { carrier => $old_carrier, sms => $old_sms },
317 { carrier => $new_carrier, sms => $new_sms },
319 $sms_changes->{$old_sms_info}
323 if ( scalar(@ffectedChgs) ){
324 $self->ctx->{affectedChgs} = \@ffectedChgs;
329 return $self->_load_user_with_prefs || Apache2::Const::OK;
332 sub _parse_prefs_notify_hold_related {
335 my $for_update = shift;
337 # create an array of change arrays
340 my @phone_notify = $self->cgi->multi_param('phone_notify[]');
341 push(@chgs, \@phone_notify) if scalar(@phone_notify);
343 my $turning_on_phone_notify = !$for_update &&
344 scalar(@phone_notify) &&
345 $phone_notify[1] eq 'true';
346 my $turning_off_phone_notify = !$for_update &&
347 scalar(@phone_notify) &&
348 $phone_notify[1] eq 'false';
350 my $changing_default_phone = 0;
351 if (!$turning_off_phone_notify) {
352 my @default_phone = $self->cgi->multi_param('default_phone[]');
354 while (scalar(@default_phone) > 0) {
355 my $chg = [ splice(@default_phone, 0, 4) ];
356 if (scalar(@default_phone) > 0 && $default_phone[0] eq 'on') {
357 push @$chg, shift(@default_phone);
359 $changing_default_phone = 1;
363 if (scalar(@default_phone)) {
364 push @chgs, \@default_phone;
365 $changing_default_phone = 1;
370 if ($turning_on_phone_notify && $changing_default_phone) {
371 # we don't need to have both the phone_notify and default_phone
372 # changes; the latter will suffice
373 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
374 } elsif ($turning_on_phone_notify && !$changing_default_phone) {
375 # replace the phone_notify change with a default_phone change
376 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
377 my $default_phone = $self->cgi->param('opac.default_phone'); # we assume this is set
378 push @chgs, [ '', $default_phone, 'default_phone' ];
382 # ... since both carrier and number are needed to send an SMS notifcation,
383 # we need to treat the pair as a unit
384 my @sms_notify = $self->cgi->multi_param('sms_notify[]');
385 push(@chgs, \@sms_notify) if scalar(@sms_notify);
387 my $turning_on_sms_notify = !$for_update &&
388 scalar(@sms_notify) &&
389 $sms_notify[1] eq 'true';
390 my $turning_off_sms_notify = !$for_update &&
391 scalar(@sms_notify) &&
392 $sms_notify[1] eq 'false';
394 my $changing_sms_info = 0;
395 if (!$turning_off_sms_notify) {
396 my @sms_carrier = $self->cgi->multi_param('default_sms_carrier_id[]');
397 my @sms = $self->cgi->multi_param('default_sms[]');
399 if (scalar(@sms) || scalar(@sms_carrier)) {
400 my $new_carrier = scalar(@sms_carrier) ? $sms_carrier[1] : $self->cgi->param('sms_carrier');
401 my $new_sms = scalar(@sms) ? $sms[1] : $self->cgi->param('opac.default_sms_notify');
403 { carrier => '', sms => '' },
404 { carrier => $new_carrier, sms => $new_sms },
407 $changing_sms_info = 1;
411 my @sms_info = $self->cgi->multi_param('sms_info[]'); # only sent by confirmation page
412 if (scalar(@sms_info)) {
413 while (scalar(@sms_info) > 0) {
414 my $chg = [ splice(@sms_info, 0, 4) ];
415 if (scalar(@sms_info) > 0 && $sms_info[0] eq 'on') {
416 push @$chg, shift(@sms_info);
417 my ($carrier, $sms) = split /,/, $chg->[0], -1;
418 $chg->[0] = { carrier => $carrier, sms => $sms };
419 ($carrier, $sms) = split /,/, $chg->[1], -1;
420 $chg->[1] = { carrier => $carrier, sms => $sms };
422 $changing_sms_info = 1;
427 if ($turning_on_sms_notify && $changing_sms_info) {
428 # we don't need to have both the sms_notify and sms_info
429 # changes; the latter will suffice
430 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
431 } elsif ($turning_on_sms_notify && !$changing_sms_info) {
432 # replace the sms_notify change with a sms_info change
433 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
435 carrier => $self->cgi->param('sms_carrier'),
436 sms => $self->cgi->param('opac.default_sms_notify'),
438 push @chgs, [ { carrier => '', sms => ''}, $sms_info, 'sms_info' ];
441 my @email_notify = $self->cgi->multi_param('email_notify[]');
442 push(@chgs, \@email_notify) if scalar(@email_notify);
445 # if we're updating, keep only the ones that have been
446 # explicitly checked by the user
447 @chgs = grep { scalar(@$_) == 5 && $_->[4] eq 'on' } @chgs;
452 sub load_myopac_prefs_notify_changed_holds {
454 my $e = $self->editor;
456 my $hasChanges = $self->cgi->param('hasHoldsChanges');
458 return $self->_load_user_with_prefs || Apache2::Const::OK unless $hasChanges;
460 my @ll = $self->_parse_prefs_notify_hold_related(1);
464 my ($old, $new, $type, $holdids, $doit) = @$chset;
465 next if $doit ne 'on';
467 # parse string list into array list
468 my @holdids = split(',', $holdids);
470 if ($type =~ /_notify/){
471 # translate true/false string into 1/0
472 $old = $old eq 'true' ? 1 : 0;
473 $new = $new eq 'true' ? 1 : 0;
477 if ($type eq 'sms_info') {
478 if ($new->{carrier} eq '' && $new->{sms} eq '') {
479 # clear SMS number first to avoid check contrainst issue
480 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
481 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
482 push (@updates, $update) if (scalar(@$update) > 0);
483 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
484 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
485 push (@updates, $update) if (scalar(@$update) > 0);
487 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
488 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
489 push (@updates, $update) if (scalar(@$update) > 0);
490 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
491 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
492 push (@updates, $update) if (scalar(@$update) > 0);
495 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
496 $e->authtoken, $e->requestor->id, [@holdids], $old, $new, $type);
498 # append affected array to chset
499 if (scalar(@$update) > 0){
500 push(@updates, $update);
505 $self->ctx->{'updated'} = \@updates;
507 return $self->_load_user_with_prefs || Apache2::Const::OK;
511 sub fetch_optin_prefs {
513 my $e = $self->editor;
515 # fetch all of the opt-in settings the user has access to
516 # XXX: user's should in theory have options to opt-in to notices
517 # for remote locations, but that opens the door for a large
518 # set of generally un-used opt-ins.. needs discussion
519 my $opt_ins = $U->simplereq(
521 'open-ils.actor.event_def.opt_in.settings.atomic',
522 $e->authtoken, $e->requestor->home_ou);
524 # some opt-ins are staff-only
525 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
527 # fetch user setting values for each of the opt-in settings
528 my $user_set = $U->simplereq(
530 'open-ils.actor.patron.settings.retrieve',
533 [map {$_->name} @$opt_ins]
536 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
539 sub load_myopac_messages {
541 my $e = $self->editor;
542 my $ctx = $self->ctx;
543 my $cgi = $self->cgi;
545 my $limit = $cgi->param('limit') || 20;
546 my $offset = $cgi->param('offset') || 0;
548 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
551 my $action = $cgi->param('action') || '';
553 my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
554 if ($changed > 0 || $failed > 0) {
555 $ctx->{message_update_action} = $action;
556 $ctx->{message_update_changed} = $changed;
557 $ctx->{message_update_failed} = $failed;
558 $self->update_dashboard_stats();
562 my $single = $cgi->param('single') || 0;
563 my $id = $cgi->param('message_id');
567 if (!$action && $single && $id) {
568 $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
569 if (scalar(@$messages) == 1) {
570 $ctx->{display_single_message} = 1;
571 $ctx->{patron_message_id} = $id;
577 # fetch all the messages
578 ($ctx->{patron_messages_count}, $messages) =
579 $self->_fetch_user_messages($pcrud, $offset, $limit);
584 foreach my $aum (@$messages) {
586 push @{ $ctx->{patron_messages} }, {
588 title => $aum->title,
589 message => $aum->message,
590 create_date => $aum->create_date,
591 edit_date => $aum->edit_date,
592 is_read => defined($aum->read_date) ? 1 : 0,
593 library => $aum->sending_lib->name,
597 $ctx->{patron_messages_limit} = $limit;
598 $ctx->{patron_messages_offset} = $offset;
600 return Apache2::Const::OK;
603 sub _fetch_and_mark_read_single_message {
608 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
609 my $messages = $pcrud->request(
610 'open-ils.pcrud.search.auml.atomic',
611 $self->editor->authtoken,
613 usr => $self->editor->requestor->id,
619 flesh_fields => { auml => ['sending_lib'] },
623 $messages->[0]->read_date('now');
625 'open-ils.pcrud.update.auml',
626 $self->editor->authtoken,
630 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
632 $self->update_dashboard_stats();
637 sub _fetch_user_messages {
643 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
645 my $all_messages = $pcrud->request(
646 'open-ils.pcrud.id_list.auml.atomic',
647 $self->editor->authtoken,
649 usr => $self->editor->requestor->id,
655 my $messages = $pcrud->request(
656 'open-ils.pcrud.search.auml.atomic',
657 $self->editor->authtoken,
659 usr => $self->editor->requestor->id,
664 flesh_fields => { auml => ['sending_lib'] },
665 order_by => { auml => 'create_date DESC' },
670 return scalar(@$all_messages), $messages;
673 sub _handle_message_action {
677 my $cgi = $self->cgi;
679 my @ids = $cgi->param('message_id');
680 return (0, 0) unless @ids;
684 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
686 my $aum = $pcrud->request(
687 'open-ils.pcrud.retrieve.auml',
688 $self->editor->authtoken,
692 if ($action eq 'mark_read') {
693 $aum->read_date('now');
694 } elsif ($action eq 'mark_unread') {
695 $aum->clear_read_date();
696 } elsif ($action eq 'mark_deleted') {
699 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
704 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
706 $failed = scalar(@ids);
708 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
710 return ($changed, $failed);
713 sub _load_lists_and_settings {
715 my $e = $self->editor;
716 my $stat = $self->_load_user_with_prefs;
719 my $setting_map = $self->ctx->{user_setting_map};
720 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
721 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
723 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
724 order_by => {cbreb => 'name'},
725 limit => $self->cgi->param('limit') || 10,
726 offset => $self->cgi->param('offset') || 0
730 # We also want a total count of the user's bookbags.
732 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
734 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
736 my $r = $e->json_query($q);
737 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
738 # Someone has requested that we use the default list's name
739 # rather than "Default List."
742 'select' => {'cbreb' => ['name']},
744 'where' => {'id' => $exclude}
746 $r = $e->json_query($q);
747 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
755 sub update_optin_prefs {
757 my $user_prefs = shift;
758 my $e = $self->editor;
759 my @settings = $self->cgi->param('setting');
762 # apply now-true settings
763 for my $applied (@settings) {
764 # see if setting is already applied to this user
765 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
766 $newsets{$applied} = OpenSRF::Utils::JSON->true;
769 # remove now-false settings
770 for my $pref (grep { $_->{value} } @$user_prefs) {
771 $newsets{$pref->{cust}->name} = undef
772 unless grep { $_ eq $pref->{cust}->name } @settings;
777 'open-ils.actor.patron.settings.update',
778 $e->authtoken, $e->requestor->id, \%newsets);
780 # update the local prefs to match reality
781 for my $pref (@$user_prefs) {
782 $pref->{value} = $newsets{$pref->{cust}->name}
783 if exists $newsets{$pref->{cust}->name};
789 sub _load_user_with_prefs {
791 my $stat = $self->prepare_extended_user_info('settings');
792 return $stat if $stat; # not-OK
794 $self->ctx->{user_setting_map} = {
795 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
796 @{$self->ctx->{user}->settings}
802 sub _get_bookbag_sort_params {
803 my ($self, $param_name) = @_;
805 # The interface that feeds this cgi parameter will provide a single
806 # argument for a QP sort filter, and potentially a modifier after a period.
807 # In practice this means the "sort" parameter will be something like
808 # "titlesort" or "authorsort.descending".
809 my $sorter = $self->cgi->param($param_name) || "";
812 $sorter =~ s/^(.*?)\.(.*)/$1/;
813 $modifier = $2 || undef;
816 return ($sorter, $modifier);
819 sub _prepare_bookbag_container_query {
820 my ($self, $container_id, $sorter, $modifier) = @_;
823 "container(bre,bookbag,%d,%s)%s%s",
824 $container_id, $self->editor->authtoken,
825 ($sorter ? " sort($sorter)" : ""),
826 ($modifier ? "#$modifier" : "")
830 sub _prepare_anonlist_sorting_query {
831 my ($self, $list, $sorter, $modifier) = @_;
834 "record_list(%s)%s%s",
836 ($sorter ? " sort($sorter)" : ""),
837 ($modifier ? "#$modifier" : "")
842 sub load_myopac_prefs_settings {
847 opac.default_search_location
848 opac.default_pickup_location
849 opac.temporary_list_no_warn
852 my $stat = $self->_load_user_with_prefs;
853 return $stat if $stat;
855 # if behind-desk holds are supported and the user
856 # setting which controls the value is opac-visible,
857 # add the setting to the list of settings to manage.
858 # note: this logic may need to be changed later to
859 # check whether behind-the-desk holds are supported
860 # anywhere the patron may select as a pickup lib.
861 my $e = $self->editor;
862 my $bdous = $self->ctx->{get_org_setting}->(
863 $e->requestor->home_ou,
864 'circ.holds.behind_desk_pickup_supported');
868 $e->retrieve_config_usr_setting_type(
869 'circ.holds_behind_desk');
871 if ($U->is_true($setting->opac_visible)) {
872 push(@user_prefs, 'circ.holds_behind_desk');
873 $self->ctx->{behind_desk_supported} = 1;
877 my $use_privacy_waiver = $self->ctx->{get_org_setting}->(
878 $e->requestor->home_ou, 'circ.privacy_waiver');
880 return Apache2::Const::OK
881 unless $self->cgi->request_method eq 'POST';
883 # some setting values from the form don't match the
884 # required value/format for the db, so they have to be
885 # individually translated.
888 my $set_map = $self->ctx->{user_setting_map};
890 foreach my $key (@user_prefs) {
891 my $val = $self->cgi->param($key);
892 $settings{$key}= $val unless $$set_map{$key} eq $val;
895 # Used by the settings update form when warning on history delete.
896 my $clear_circ_history = 0;
897 my $clear_hold_history = 0;
899 # true if we need to show the warning on next page load.
900 my $hist_warning_needed = 0;
901 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
903 my $now = DateTime->now->strftime('%F');
905 qw/history.circ.retention_start history.hold.retention_start/) {
907 my $val = $self->cgi->param($key);
908 if($val and $val eq 'on') {
909 # Set the start time to 'now' unless a start time already exists for the user
910 $settings{$key} = $now unless $$set_map{$key};
914 next unless $$set_map{$key}; # nothing to do
916 $clear_circ_history = 1 if $key =~ /circ/;
917 $clear_hold_history = 1 if $key =~ /hold/;
919 if (!$hist_clear_confirmed) {
920 # when clearing circ history, only warn if history data exists.
922 if ($clear_circ_history) {
924 if ($self->fetch_user_circ_history(0, 1)->[0]) {
925 $hist_warning_needed = 1;
926 next; # no history updates while confirmation pending
931 my $one_hold = $e->json_query({
935 transform => 'action.usr_visible_holds',
940 where => {id => $e->requestor->id},
945 $hist_warning_needed = 1;
946 next; # no history updates while confirmation pending
951 $settings{$key} = undef;
953 if ($key eq 'history.circ.retention_start') {
954 # delete existing circulation history data.
957 'open-ils.actor.history.circ.clear',
958 $self->editor->authtoken);
963 # Warn patrons before clearing circ/hold history
964 if ($hist_warning_needed) {
965 $self->ctx->{clear_circ_history} = $clear_circ_history;
966 $self->ctx->{clear_hold_history} = $clear_hold_history;
967 $self->ctx->{confirm_history_delete} = 1;
970 # Send the modified settings off to be saved
973 'open-ils.actor.patron.settings.update',
974 $self->editor->authtoken, undef, \%settings);
976 $self->ctx->{updated_user_settings} = \%settings;
978 if ($use_privacy_waiver) {
980 my $saved_entries = ();
981 my @waiver_types = qw/place_holds pickup_holds checkout_items view_history/;
983 # initialize our waiver hash with waiver IDs from hidden input
984 # (this ensures that we capture entries with no checked boxes)
985 foreach my $waiver_row_id ($self->cgi->param("waiver_id")) {
986 $waiver{$waiver_row_id} = {};
989 # process our waiver checkboxes into a hash, keyed by waiver ID
990 # (a new entry, if any, has id = 'new')
991 foreach my $waiver_type (@waiver_types) {
992 if ($self->cgi->param("waiver_$waiver_type")) {
993 foreach my $waiver_id ($self->cgi->param("waiver_$waiver_type")) {
994 # ensure this waiver exists in our hash
995 $waiver{$waiver_id} = {} if !$waiver{$waiver_id};
996 $waiver{$waiver_id}->{$waiver_type} = 1;
1001 foreach my $k (keys %waiver) {
1002 my $w = $waiver{$k};
1003 # get name from textbox
1004 $w->{name} = $self->cgi->param("waiver_name_$k");
1006 foreach (@waiver_types) {
1007 $w->{$_} = 0 unless ($w->{$_});
1009 push @$saved_entries, $w;
1012 # update patron privacy waiver entries
1015 'open-ils.actor.patron.privacy_waiver.update',
1016 $self->editor->authtoken, undef, $saved_entries);
1018 $self->ctx->{updated_waiver_entries} = $saved_entries;
1021 # re-fetch user prefs
1022 return $self->_load_user_with_prefs || Apache2::Const::OK;
1025 sub load_myopac_prefs_my_lists {
1028 my @user_prefs = qw/
1030 opac.list_items_per_page
1033 my $stat = $self->_load_user_with_prefs;
1034 return $stat if $stat;
1036 return Apache2::Const::OK
1037 unless $self->cgi->request_method eq 'POST';
1040 my $set_map = $self->ctx->{user_setting_map};
1042 foreach my $key (@user_prefs) {
1043 my $val = $self->cgi->param($key);
1044 $settings{$key}= $val unless $$set_map{$key} eq $val;
1047 if (keys %settings) { # we found a different setting value
1048 # Send the modified settings off to be saved
1051 'open-ils.actor.patron.settings.update',
1052 $self->editor->authtoken, undef, \%settings);
1054 # re-fetch user prefs
1055 $self->ctx->{updated_user_settings} = \%settings;
1056 $stat = $self->_load_user_with_prefs;
1059 return $stat || Apache2::Const::OK;
1062 sub fetch_user_holds {
1064 my $hold_ids = shift;
1065 my $ids_only = shift;
1067 my $available = shift;
1071 my $e = $self->editor;
1072 my $all_ids; # to be used below.
1075 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1077 $hold_ids = $circ->request(
1078 'open-ils.circ.holds.id_list.retrieve.authoritative',
1085 $all_ids = $hold_ids;
1086 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
1089 $all_ids = $hold_ids;
1092 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
1095 suppress_notices => 1,
1096 suppress_transits => 1,
1098 suppress_patron_details => 1
1101 # ----------------------------------------------------------------
1102 # Collect holds in batches of $batch_size for faster retrieval
1106 my $mk_req_batch = sub {
1108 my $top_idx = $batch_idx + $batch_size;
1109 while($batch_idx < $top_idx) {
1110 my $hold_id = $hold_ids->[$batch_idx++];
1111 last unless $hold_id;
1112 my $ses = OpenSRF::AppSession->create('open-ils.circ');
1113 my $req = $ses->request(
1114 'open-ils.circ.hold.details.retrieve',
1115 $e->authtoken, $hold_id, $args);
1116 push(@ses, {ses => $ses, req => $req});
1122 my(@collected, @holds, @ses);
1125 @ses = $mk_req_batch->() if $first;
1126 last if $first and not @ses;
1129 while(my $blob = pop(@collected)) {
1132 # in the holds edit UI, we need to know what formats and
1133 # languages the user selected for this hold, plus what
1134 # formats/langs are available on the MR as a whole.
1135 if ($blob->{hold}{hold}->hold_type eq 'M') {
1136 my $hold = $blob->{hold}->{hold};
1138 # for MR, fetch the combined MR unapi blob
1139 (undef, @data) = $self->get_records_and_facets(
1140 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
1142 my $filter_org = $U->org_unit_ancestor_at_depth(
1143 $hold->selection_ou,
1144 $hold->selection_depth);
1146 my $filter_data = $U->simplereq(
1148 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
1149 $hold->target, $filter_org, [$hold->id]
1152 $blob->{metarecord_filters} =
1153 $filter_data->[0]->{metarecord};
1154 $blob->{metarecord_selected_filters} =
1155 $filter_data->[1]->{hold};
1158 (undef, @data) = $self->get_records_and_facets(
1159 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
1163 $blob->{marc_xml} = $data[0]->{marc_xml};
1164 push(@holds, $blob);
1168 for my $req_data (@ses) {
1169 push(@collected, {hold => $req_data->{req}->gather(1)});
1170 $req_data->{ses}->kill_me;
1173 @ses = $mk_req_batch->();
1174 last unless @collected or @ses;
1178 # put the holds back into the original server sort order
1180 for my $id (@$hold_ids) {
1181 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1185 try { # if the service is not running, just let this fail silently
1186 $curbsides = $U->simplereq(
1187 'open-ils.curbside',
1188 'open-ils.curbside.fetch_mine.atomic',
1191 } catch Error with {};
1193 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, curbsides => $curbsides };
1196 sub load_current_curbside_libs {
1198 my $ctx = $self->ctx;
1199 my $e = $self->editor;
1200 my $holds = $e->search_action_hold_request({
1201 usr => $e->requestor->id,
1202 shelf_time => { '!=' => undef },
1203 cancel_time => undef,
1204 fulfillment_time => undef
1208 for my $h (@$holds) {
1209 next if ($h->pickup_lib != $h->current_shelf_lib);
1210 $pickup_libs{$h->pickup_lib} = 1;
1213 my @curbside_pickup_libs;
1214 for my $pul (keys %pickup_libs) {
1215 push(@curbside_pickup_libs, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1218 $ctx->{curbside_pickup_libs} = [
1219 sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } @curbside_pickup_libs
1223 sub handle_hold_update {
1226 my $hold_ids = shift;
1227 my $e = $self->editor;
1228 my $ctx = $self->ctx;
1231 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1232 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1234 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1236 if($action =~ /cancel/) {
1238 for my $hold_id (@hold_ids) {
1239 my $resp = $circ->request(
1240 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1243 } elsif ($action =~ /activate|suspend/) {
1246 for my $hold_id (@hold_ids) {
1247 my $vals = {id => $hold_id};
1249 if($action =~ /activate/) {
1250 $vals->{frozen} = 'f';
1251 $vals->{thaw_date} = undef;
1253 } elsif($action =~ /suspend/) {
1254 $vals->{frozen} = 't';
1255 # $vals->{thaw_date} = TODO;
1257 push(@$vlist, $vals);
1260 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1261 $self->ctx->{hold_suspend_post_capture} = 1 if
1262 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1264 } elsif ($action eq 'edit') {
1267 my $val = {"id" => $_};
1268 $val->{"frozen"} = $self->cgi->param("frozen");
1269 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1270 $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1271 $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1272 $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1273 $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1275 for my $field (qw/expire_time thaw_date/) {
1276 # XXX TODO make this support other date formats, not just
1278 next unless $self->cgi->param($field) =~
1279 m:^(\d{2})/(\d{2})/(\d{4})$:;
1280 $val->{$field} = "$3-$1-$2";
1283 $val->{holdable_formats} = # no-op for non-MR holds
1284 $self->compile_holdable_formats(undef, $_);
1290 'open-ils.circ.hold.update.batch.atomic',
1291 $e->authtoken, undef, \@vals
1292 )->gather(1); # LFW XXX test for failure
1293 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1294 foreach my $param (('loc', 'qtype', 'query')) {
1295 if ($self->cgi->param($param)) {
1296 my @vals = $self->cgi->param($param);
1297 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1300 } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1303 $circ = OpenSRF::AppSession->create('open-ils.curbside');
1305 # see what we're doing with curbside here...
1306 my $cs_action = $self->cgi->param("cs_action");
1307 my $slot_id = $self->cgi->param("cs_slot_id");
1309 # we have an id, let's grab it if we can
1310 my $slot = $e->retrieve_action_curbside($slot_id);
1311 $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1313 my $org = $self->cgi->param("cs_org");
1314 my $date = $self->cgi->param("cs_date");
1315 my $time = $self->cgi->param("cs_time");
1316 my $notes = $self->cgi->param("cs_notes");
1319 $org ||= $slot->org;
1320 $notes ||= $slot->notes;
1322 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1323 $date ||= $dt->strftime('%F');
1324 $time ||= $dt->strftime('%T');
1328 $ctx->{cs_org} = $org;
1329 $ctx->{cs_date} = $date;
1330 $ctx->{cs_time} = $time;
1331 $ctx->{cs_notes} = $notes;
1332 $ctx->{cs_slot_id} = $slot->id if ($slot);
1333 $ctx->{cs_slot} = $slot;
1335 if ($cs_action eq 'reset') {
1336 $ctx->{cs_org} = $org = undef;
1337 $ctx->{cs_date} = $date = undef;
1338 $ctx->{cs_time} = $time = undef;
1339 $ctx->{cs_notes} = $notes = undef;
1340 $ctx->{cs_slot_id} = $slot_id = undef;
1341 $ctx->{cs_slot} = $slot = undef;
1342 } elsif ($cs_action eq 'save' && $org && $date && $time) {
1343 my $mode = $slot ? 'update' : 'create';
1344 $slot = $circ->request(
1345 "open-ils.curbside.${mode}_appointment",
1346 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1349 if (defined $U->event_code($slot)) {
1350 $self->apache->log->warn(
1351 "error attempting to $mode a curbside appointment for patron ".
1352 $e->requestor->id . ", got event " . $slot->{textcode}
1354 $ctx->{curbside_action_event} = $slot;
1355 $ctx->{cs_slot} = undef;
1357 $ctx->{cs_slot} = $slot;
1359 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1360 } elsif ($cs_action eq 'cancel' && $slot) {
1361 my $curbsides = $U->simplereq(
1362 'open-ils.curbside',
1363 'open-ils.curbside.delete_appointment',
1364 $e->authtoken, $slot->id
1366 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1367 } elsif ($cs_action eq 'arrive' && $slot) {
1368 my $curbsides = $U->simplereq(
1369 'open-ils.curbside',
1370 'open-ils.curbside.mark_arrived',
1371 $e->authtoken, $slot->id
1373 } elsif ($cs_action eq 'deliver' && $slot) {
1374 my $curbsides = $U->simplereq(
1375 'open-ils.curbside',
1376 'open-ils.curbside.mark_delivered',
1377 $e->authtoken, $slot->id
1381 if ($date and $org and !$ctx->{cs_times}{$org}{$date}) {
1382 $ctx->{cs_times}{$org}{$date} = $circ->request(
1383 'open-ils.curbside.times_for_date.atomic',
1384 $e->authtoken, $date, $org
1390 return defined($url) ? $self->generic_redirect($url) : undef;
1393 sub load_myopac_holds {
1395 my $e = $self->editor;
1396 my $ctx = $self->ctx;
1398 my $limit = $self->cgi->param('limit') || 15;
1399 my $offset = $self->cgi->param('offset') || 0;
1400 my $action = $self->cgi->param('action') || '';
1401 my $hold_id = $self->cgi->param('hid');
1402 my $available = int($self->cgi->param('available') || 0);
1404 my $hold_handle_result;
1405 $hold_handle_result = $self->handle_hold_update($action) if $action;
1408 if ($self->cgi->param('sort') ne "") {
1409 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1412 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1415 if($holds_object->{holds}) {
1416 $ctx->{holds} = $holds_object->{holds};
1417 $ctx->{curbside_appointments} = {};
1419 $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1421 for my $cs (@{$holds_object->{curbsides}}) {
1423 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1424 $ctx->{cs_times}{$cs->org}{$dt} = $U->simplereq(
1425 'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1426 $e->authtoken, $dt, $cs->org
1429 $ctx->{curbside_appointments}{$cs->org} = $cs;
1432 $ctx->{holds_ids} = $holds_object->{all_ids};
1433 $ctx->{holds_limit} = $limit;
1434 $ctx->{holds_offset} = $offset;
1436 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1439 sub load_myopac_hold_subscriptions {
1441 my $e = $self->editor;
1442 my $ctx = $self->ctx;
1444 my $sub_remove = $self->cgi->param('remove');
1446 if ($sub_remove and $ctx->{user}->id) {
1447 my $sub_entries = $self->editor->search_container_user_bucket_item(
1448 { bucket => $sub_remove, target_user => $ctx->{user}->id }
1451 $self->editor->xact_begin;
1452 $self->editor->delete_container_user_bucket_item($_) for @$sub_entries;
1453 $self->editor->xact_commit;
1455 return $self->generic_redirect(
1456 $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/hold_subscriptions'
1460 return Apache2::Const::OK;
1465 sub load_place_hold {
1467 my $ctx = $self->ctx;
1468 my $gos = $ctx->{get_org_setting};
1469 my $e = $self->editor;
1470 my $cgi = $self->cgi;
1472 $self->ctx->{page} = 'place_hold';
1473 my @targets = uniq $cgi->param('hold_target');
1474 my @parts = $cgi->param('part');
1476 $ctx->{hold_subscription} = $cgi->param('hold_subscription');
1477 $ctx->{hold_type} = $cgi->param('hold_type');
1478 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1479 $ctx->{email_notify} = $cgi->param('email_notify');
1480 if ($cgi->param('phone_notify_checkbox')) {
1481 $ctx->{phone_notify} = $cgi->param('phone_notify');
1483 if ($cgi->param('sms_notify_checkbox')) {
1484 $ctx->{sms_notify} = $cgi->param('sms_notify');
1485 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1488 return $self->generic_redirect unless @targets;
1490 # Check for multiple hold placement via the num_copies widget.
1491 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1492 if ($num_copies > 1) {
1493 # Only if we have 1 hold target and no parts.
1494 if (scalar(@targets) == 1 && !$parts[0]) {
1495 # Also, only for M and T holds.
1496 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1497 # Add the extra holds to @targets. NOTE: We start with
1498 # 1 and go to < $num_copies to account for the
1500 for (my $i = 1; $i < $num_copies; $i++) {
1501 push(@targets, $targets[0]);
1507 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1509 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1514 au => ['settings', 'card']
1517 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1518 my $user_setting_map = {
1519 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1521 $ctx->{staff_recipient}->settings
1524 $ctx->{user_setting_map} = $user_setting_map;
1526 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1527 if ($default_notify =~ /email/) {
1528 $ctx->{default_email_notify} = 'checked';
1530 $ctx->{default_email_notify} = '';
1532 if ($default_notify =~ /phone/) {
1533 $ctx->{default_phone_notify} = 'checked';
1535 $ctx->{default_phone_notify} = '';
1537 if ($default_notify =~ /sms/) {
1538 $ctx->{default_sms_notify} = 'checked';
1540 $ctx->{default_sms_notify} = '';
1542 if ($cgi->param('hold_suspend')) {
1544 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1545 # We should use a date input type on the forms once it is supported by Firefox.
1546 # I didn't do that now because it is not available in a general release.
1547 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1549 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1550 $ctx->{thaw_date} = $dt->ymd;
1553 $logger->warn("ignoring invalid thaw_date when placing hold request");
1559 # If we have a default pickup location, grab it
1560 if ($$user_setting_map{'opac.default_pickup_location'}) {
1561 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1564 my $request_lib = $e->requestor->ws_ou;
1566 $ctx->{hold_data} = \@hold_data;
1568 $data_filler = sub {
1570 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1571 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1572 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1573 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1574 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1575 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1579 my $type_dispatch = {
1581 # target metarecords
1582 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1584 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1588 for my $id (@targets) {
1589 my ($mr) = grep {$_->id eq $id} @$mrecs;
1591 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1592 my $filter_data = $U->simplereq(
1594 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1596 my $holdable_formats =
1597 $self->compile_holdable_formats($mr->id);
1599 push(@hold_data, $data_filler->({
1601 record => $mr->master_record,
1602 holdable_formats => $holdable_formats,
1603 metarecord_filters => $filter_data->{metarecord}
1608 my $recs = $e->batch_retrieve_biblio_record_entry(
1609 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1613 for my $id (@targets) { # force back into the correct order
1614 my ($rec) = grep {$_->id eq $id} @$recs;
1616 # NOTE: if tpac ever supports locked-down pickup libs,
1617 # we'll need to pass a pickup_lib param along with the
1618 # record to filter the set of monographic parts.
1619 my $parts = $U->simplereq(
1621 'open-ils.search.biblio.record_hold_parts',
1622 {record => $rec->id}
1625 # T holds on records that have parts are OK, but if the record has
1626 # no non-part copies, the hold will ultimately fail. When that
1627 # happens, require the user to select a part.
1628 my $part_required = 0;
1630 my $np_copies = $e->json_query({
1631 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1632 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1634 '+acp' => {deleted => 'f'},
1635 '+acn' => {deleted => 'f', record => $rec->id},
1636 '+acpm' => {id => undef}
1639 $part_required = 1 if $np_copies->[0]->{count} == 0;
1642 push(@hold_data, $data_filler->({
1646 part_required => $part_required
1651 my $vols = $e->batch_retrieve_asset_call_number([
1654 "flesh_fields" => {"acn" => ["record"]}
1656 ], {substream => 1});
1658 for my $id (@targets) {
1659 my ($vol) = grep {$_->id eq $id} @$vols;
1660 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1664 my $copies = $e->batch_retrieve_asset_copy([
1668 "acn" => ["record"],
1669 "acp" => ["call_number"]
1672 ], {substream => 1});
1674 for my $id (@targets) {
1675 my ($copy) = grep {$_->id eq $id} @$copies;
1676 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1680 my $isses = $e->batch_retrieve_serial_issuance([
1684 "siss" => ["subscription"], "ssub" => ["record_entry"]
1687 ], {substream => 1});
1689 for my $id (@targets) {
1690 my ($iss) = grep {$_->id eq $id} @$isses;
1691 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1696 }->{$ctx->{hold_type}}->();
1698 # caller sent bad target IDs or the wrong hold type
1699 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1701 # generate the MARC xml for each record
1702 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1704 my $pickup_lib = $cgi->param('pickup_lib');
1705 # no pickup lib means no holds placement, except for subscriptions
1706 return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1708 $ctx->{hold_attempt_made} = 1;
1710 # Give the original CGI params back to the user in case they
1711 # want to try to override something.
1712 $ctx->{orig_params} = $cgi->Vars;
1713 delete $ctx->{orig_params}{submit};
1714 delete $ctx->{orig_params}{hold_target};
1715 delete $ctx->{orig_params}{part};
1717 my $usr = $e->requestor->id;
1719 if ($ctx->{is_staff}) {
1720 $logger->info("Staff initiated hold");
1721 if (!$cgi->param("hold_usr_is_requestor")) {
1722 # find the real hold target
1724 $usr = $U->simplereq(
1726 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1727 $e->authtoken, $cgi->param("hold_usr"));
1729 if (defined $U->event_code($usr)) {
1730 $ctx->{hold_failed} = 1;
1731 $ctx->{hold_failed_event} = $usr;
1735 if ($ctx->{hold_subscription}) {
1736 # this is a batch event, hold "user" is a bucket id
1737 $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1738 $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1742 # target_id is the true target_id for holds placement.
1743 # needed for attempt_hold_placement()
1744 # With the exception of P-type holds, target_id == target->id.
1745 $_->{target_id} = $_->{target}->id for @hold_data;
1747 if ($ctx->{hold_type} eq 'T') {
1749 # Much like quantum wave-particles, P-type holds pop into
1750 # and out of existence at the user's whim. For our purposes,
1751 # we treat such holds as T(itle) holds with a selected_part
1752 # designation. When the time comes to pass the hold information
1753 # off for holds possibility testing and placement, make it look
1754 # like a real P-type hold.
1755 my (@p_holds, @t_holds);
1757 # Now that we have the num_copies field for mutliple title and
1758 # metarecord hold placement, the number of holds and parts
1759 # arrays can get out of sync. We only want to parse out parts
1760 # if the numbers are equal.
1761 if ($#hold_data == $#parts) {
1762 for my $idx (0..$#parts) {
1763 my $hdata = $hold_data[$idx];
1764 if (my $part = $parts[$idx]) {
1765 $hdata->{target_id} = $part;
1766 $hdata->{selected_part} = $part;
1767 push(@p_holds, $hdata);
1769 push(@t_holds, $hdata);
1773 @t_holds = @hold_data;
1776 $self->apache->log->warn("$#parts : @t_holds");
1778 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1779 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1782 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1785 # NOTE: we are leaving the staff-placed patron barcode cookie
1786 # in place. Otherwise, it's not possible to place more than
1787 # one hold for the patron within a staff/patron session. This
1788 # does leave the barcode to linger longer than is ideal, but
1789 # normal staff work flow will cause the cookie to be replaced
1790 # with each new patron anyway.
1791 # TODO: See about getting the staff client to clear the cookie
1793 # return to the place_hold page so the results of the hold
1794 # placement attempt can be reported to the user
1795 return Apache2::Const::OK;
1798 sub attempt_hold_placement {
1799 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1800 my $cgi = $self->cgi;
1801 my $ctx = $self->ctx;
1802 my $e = $self->editor;
1804 my $user_container = undef;
1805 if (ref($usr)) { # $usr is actually a container for a subscription...
1806 $user_container = $usr->id;
1807 return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1810 # First see if we should warn/block for any holds that
1811 # might have locally available items for non-subscriptions.
1812 if (!$user_container) {
1813 for my $hdata (@hold_data) {
1814 my ($local_block, $local_alert) = $self->local_avail_concern(
1815 $hdata->{target_id}, $hold_type, $pickup_lib);
1818 $hdata->{hold_failed} = 1;
1819 $hdata->{hold_local_block} = 1;
1820 } elsif ($local_alert) {
1821 $hdata->{hold_failed} = 1;
1822 $hdata->{hold_local_alert} = 1;
1827 my $method = $user_container
1828 ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1829 : 'open-ils.circ.holds.test_and_create.batch';
1831 if ($cgi->param('override')) {
1832 $method .= '.override';
1834 } elsif (!$ctx->{is_staff}) {
1836 $method .= '.override' if $self->ctx->{get_org_setting}->(
1837 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1840 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1843 if(@create_targets) {
1845 # holdable formats may be different for each MR hold.
1846 # map each set to the ID of the target.
1847 my $holdable_formats = {};
1848 if ($hold_type eq 'M') {
1849 $holdable_formats->{$_->{target_id}} =
1850 $_->{holdable_formats} for @hold_data;
1853 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1855 my @create_params = ();
1857 if ($user_container) {
1860 hold_type => $hold_type,
1861 holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1870 pickup_lib => $pickup_lib,
1871 hold_type => $hold_type,
1872 holdable_formats_map => $holdable_formats,
1878 my $breq = $bses->request($method, $e->authtoken, @create_params);
1880 while (my $resp = $breq->recv) {
1882 $resp = $resp->content;
1883 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1885 if ($U->event_code($resp)) {
1886 $ctx->{general_hold_error} = $resp;
1890 # subscription batch create sends an initial response to assist with client-side counting
1893 defined($$resp{count}) and $$resp{count} == 0
1894 and defined($$resp{total}) and $$resp{total} > 0
1897 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1898 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1899 my $result = $resp->{result};
1901 if ($U->event_code($result)) {
1902 # e.g. permission denied
1903 $hdata->{hold_failed} = 1;
1904 $hdata->{hold_failed_event} = $result;
1908 if(not ref $result and $result > 0) {
1909 # successul hold returns the hold ID
1910 $hdata->{hold_success} = $result;
1913 # hold-specific failure event
1914 $hdata->{hold_failed} = 1;
1916 if (ref $result eq 'HASH') {
1917 $hdata->{hold_failed_event} = $result->{last_event};
1919 if ($result->{age_protected_copy}) {
1920 my %temp = %{$hdata->{hold_failed_event}};
1921 my $theTextcode = $temp{"textcode"};
1922 $theTextcode.=".override";
1923 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1924 $hdata->{age_protect} = 1;
1926 $hdata->{could_override} = $result->{place_unfillable} ||
1927 $self->test_could_override($hdata->{hold_failed_event});
1929 } elsif (ref $result eq 'ARRAY') {
1930 $hdata->{hold_failed_event} = $result->[0];
1932 if ($result->[3]) { # age_protect_only
1933 my %temp = %{$hdata->{hold_failed_event}};
1934 my $theTextcode = $temp{"textcode"};
1935 $theTextcode.=".override";
1936 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1937 $hdata->{age_protect} = 1;
1939 $hdata->{could_override} = $result->[4] || # place_unfillable
1940 $self->test_could_override($hdata->{hold_failed_event});
1950 if ($self->cgi->param('clear_cart')) {
1951 $self->clear_anon_cache;
1955 # pull the selected formats and languages for metarecord holds
1956 # from the CGI params and map them into the JSON holdable
1957 # formats...er, format.
1958 # if no metarecord is provided, we'll pull it from the target
1959 # of the provided hold.
1960 sub compile_holdable_formats {
1961 my ($self, $mr_id, $hold_id) = @_;
1962 my $e = $self->editor;
1963 my $cgi = $self->cgi;
1965 # exit early if not needed
1967 grep /metarecord_formats_|metarecord_langs_/,
1970 # CGI params are based on the MR id, since during hold placement
1971 # we have no old ID. During hold edit, map the hold ID back to
1972 # the metarecod target.
1974 $e->retrieve_action_hold_request($hold_id)->target
1977 my $format_attr = $self->ctx->{get_cgf}->(
1978 'opac.metarecord.holds.format_attr');
1980 if (!$format_attr) {
1981 $logger->error("Missing config.global_flag: ".
1982 "opac.metarecord.holds.format_attr!");
1986 $format_attr = $format_attr->value;
1988 # during hold placement or edit submission, the user selects
1989 # which of the available formats/langs are acceptable.
1990 # Capture those here as the holdable_formats for the MR hold.
1991 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1992 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1994 # map the selected attrs into the JSON holdable_formats structure
1996 if (@selected_formats) {
1998 map { {_attr => $format_attr, _val => $_} }
2002 if (@selected_langs) {
2004 map { {_attr => 'item_lang', _val => $_} }
2009 return OpenSRF::Utils::JSON->perl2JSON($blob);
2012 sub fetch_user_circs {
2014 my $flesh = shift; # flesh bib data, etc.
2015 my $circ_ids = shift;
2019 my $e = $self->editor;
2024 @circ_ids = @$circ_ids;
2029 select => {circ => ['id']},
2033 usr => $e->requestor->id,
2034 checkin_time => undef,
2036 {stop_fines => undef},
2037 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2041 order_by => {circ => ['due_date']}
2044 $query->{limit} = $limit if $limit;
2045 $query->{offset} = $offset if $offset;
2047 my $ids = $e->json_query($query);
2048 @circ_ids = map {$_->{id}} @$ids;
2051 return [] unless @circ_ids;
2056 circ => ['target_copy'],
2057 acp => ['call_number','parts'],
2058 acn => ['record','owning_lib','prefix','suffix']
2063 my $circs = $e->search_action_circulation(
2064 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2067 for my $circ (@$circs) {
2070 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2071 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2072 undef # pre-cat copy, use the dummy title/author instead
2077 # make sure the final list is in the correct order
2079 for my $id (@circ_ids) {
2082 (grep { $_->{circ}->id == $id } @circs)
2086 return \@sorted_circs;
2090 sub handle_circ_renew {
2093 my $ctx = $self->ctx;
2095 my @renew_ids = $self->cgi->param('circ');
2097 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2099 # TODO: fire off renewal calls in batches to speed things up
2101 for my $circ (@$circs) {
2103 my $evt = $U->simplereq(
2105 'open-ils.circ.renew',
2106 $self->editor->authtoken,
2108 patron_id => $self->editor->requestor->id,
2109 copy_id => $circ->{circ}->target_copy,
2114 # TODO return these, then insert them into the circ data
2115 # blob that is shoved into the template for each circ
2116 # so the template won't have to match them
2117 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2123 sub load_myopac_circs {
2125 my $e = $self->editor;
2126 my $ctx = $self->ctx;
2129 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2130 my $offset = $self->cgi->param('offset') || 0;
2131 my $action = $self->cgi->param('action') || '';
2133 # perform the renewal first if necessary
2134 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2136 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2138 my $success_renewals = 0;
2139 my $failed_renewals = 0;
2140 for my $data (@{$ctx->{circs}}) {
2141 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2144 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2146 # extract the fail_part, if present, from the event payload;
2147 # since # the payload is an acp object in some cases,
2148 # blindly looking for a # 'fail_part' key in the template can
2150 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2151 $evt->{payload}->{fail_part} :
2154 $data->{renewal_response} = $evt;
2155 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2156 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2160 $ctx->{success_renewals} = $success_renewals;
2161 $ctx->{failed_renewals} = $failed_renewals;
2163 return Apache2::Const::OK;
2166 sub load_myopac_circ_history {
2168 my $e = $self->editor;
2169 my $ctx = $self->ctx;
2170 my $limit = $self->cgi->param('limit') || 15;
2171 my $offset = $self->cgi->param('offset') || 0;
2172 my $action = $self->cgi->param('action') || '';
2174 my $circ_handle_result;
2175 $circ_handle_result = $self->handle_circ_update($action) if $action;
2177 $ctx->{circ_history_limit} = $limit;
2178 $ctx->{circ_history_offset} = $offset;
2180 # Defer limitation to circ_history.tt2 when sorting
2181 if ($self->cgi->param('sort')) {
2186 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2187 return Apache2::Const::OK;
2190 # if 'flesh' is set, copy data etc. is loaded and the return value is
2191 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2193 sub fetch_user_circ_history {
2194 my ($self, $flesh, $limit, $offset) = @_;
2195 my $e = $self->editor;
2198 $limits{offset} = $offset if defined $offset;
2199 $limits{limit} = $limit if defined $limit;
2204 auch => ['target_copy','source_circ'],
2205 acp => ['call_number','parts'],
2206 acn => ['record','prefix','suffix']
2211 my $circs = $e->search_action_user_circ_history(
2213 {usr => $e->requestor->id},
2214 { # order newest to oldest by default
2215 order_by => {auch => 'xact_start DESC'},
2216 $flesh ? %flesh_ops : (),
2224 return $circs unless $flesh;
2228 my %unapi_cache = ();
2229 for my $circ (@$circs) {
2230 if ($circ->target_copy->call_number->id == -1) {
2233 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2237 my $bre_id = $circ->target_copy->call_number->record->id;
2239 if (exists $unapi_cache{$bre_id}) {
2240 $unapi = $unapi_cache{$bre_id};
2242 my $result = $e->json_query({
2244 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2248 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2259 marc_xml => undef # failed, but try to go on
2268 sub handle_circ_update {
2271 my $circ_ids = shift;
2273 $circ_ids //= [$self->cgi->param('circ_id')];
2275 if ($action =~ /delete/) {
2277 circ_ids => $circ_ids,
2282 'open-ils.actor.history.circ.clear',
2283 $self->editor->authtoken,
2291 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2292 sub load_myopac_hold_history {
2294 my $e = $self->editor;
2295 my $ctx = $self->ctx;
2296 my $limit = $self->cgi->param('limit') || 15;
2297 my $offset = $self->cgi->param('offset') || 0;
2298 $ctx->{hold_history_limit} = $limit;
2299 $ctx->{hold_history_offset} = $offset;
2301 my $hold_ids = $e->json_query({
2305 transform => 'action.usr_visible_holds',
2306 result_field => 'id'
2310 where => {id => $e->requestor->id}
2313 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2314 if($holds_object->{holds}) {
2315 $ctx->{holds} = $holds_object->{holds};
2317 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2319 return Apache2::Const::OK;
2322 sub load_myopac_payment_form {
2325 my $e = $self->editor;
2327 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2329 if ( ! $self->cgi->param('last_chance')) { # only do this once
2330 if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2331 if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')) {
2332 my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2333 my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2334 my $stripe = Business::Stripe->new(-api_key => $skey);
2335 my $intent = $stripe->api('post', 'payment_intents',
2336 amount => $self->ctx->{fines}->{balance_owed} * 100,
2337 currency => $currency || 'usd',
2338 description => 'User Database ID: ' . $self->ctx->{user}->id
2340 if ($stripe->success) {
2341 $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2343 $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2344 $self->ctx->{cc_configuration_error} = 1;
2347 } elsif ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'SmartPAY') {
2348 if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.enabled')) {
2349 my $location_id = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.location_id'));
2350 $self->ctx->{smartpay_locationid} = $location_id;
2351 my $customer_id = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.customer_id'));
2352 $self->ctx->{smartpay_customerid} = $customer_id;
2353 my $login = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.login'));
2354 my $password = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.password'));
2355 my $api_key = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.api_key'));
2356 my $server = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.server'));
2357 my $port = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.port'));
2358 my $base_target = "https://$server";
2359 $base_target .= ":$port" if $port;
2360 $base_target .= "/SMARTPAYAPI/WEBSMARTPAY.dll";
2363 my $target = $base_target . "?RequestSessionKey";
2364 $target .= "&CustomerID=$customer_id";
2365 $target .= "&LocationID=$location_id";
2366 $target .= "&UserName=$login";
2367 $target .= "&Password=$password";
2368 $target .= "&APIKey=$api_key";
2370 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2371 #$logger->error('SmartPAY debug, cache_args = ' . Dumper($cache_args) );
2373 # generate a temporary cache token for our secret
2374 my $token = 'smartpay_' . md5_hex($$ . time() . rand());
2375 $target .= "&Secret=$token";
2377 #$logger->error('SmartPAY debug, target= $target ' . Dumper($target) );
2379 my $ua = new LWP::UserAgent;
2381 # there has been API flux with whether to send API-Key and Secret as HTTP headers or URL params
2382 #my $req = GET($target, 'API-Key' => "$api_key", 'Secret' => "$token");
2383 my $req = GET($target);
2384 my $response = $ua->request($req);
2386 if ($response->is_success() && $response->content() !~ /HTML/) {
2387 $logger->info('SmartPAY initialized for ' . $self->editor->authtoken);
2389 my $session_key = $response->content();
2391 # we'll test this secret key again in the create payment method
2393 user => $self->ctx->{user}->id,
2394 session_key => $session_key
2396 my $cache = OpenSRF::Utils::Cache->new('global');
2397 $cache->put_cache($token, $cache_args, 300);
2399 # this will be for our follow-up call client-side
2401 $self->ctx->{smartpay_target} = $base_target . '?GetCreditForm';
2402 $self->ctx->{smartpay_target} .= '&SessionKey=' . $session_key;
2403 $self->ctx->{smartpay_target} .= "&CustomerID=$customer_id";
2404 $self->ctx->{smartpay_target} .= "&LocationID=$location_id";
2405 $self->ctx->{smartpay_target} .= '&PatronID=' . $self->ctx->{user}->id; # $e->requestor->id;
2406 $self->ctx->{smartpay_target} .= '&InvNum=1234';
2407 $self->ctx->{smartpay_target} .= '&Amount=' . $self->ctx->{fines}->{balance_owed};
2408 $self->ctx->{smartpay_target} .= '&URLPostBack=' . CGI::escapeHTML( $self->ctx->{hostname} );
2409 #$self->ctx->{smartpay_target} .= '&ScriptPostBack=' . CGI::escapeHTML('/cgi-bin/offline/echo1.pl');
2410 $self->ctx->{smartpay_target} .= '&URLReturn=' . CGI::escapeHTML( $self->ctx->{opac_root} . '/myopac/main_pay_init' );
2411 $self->ctx->{smartpay_target} .= '&URLCancel=' . CGI::escapeHTML( 'https://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/charges');
2412 $self->ctx->{smartpay_target} .= '&UserName=&Password=&Field1=smartpay&Field2=&Field3=&ItemsData=';
2415 my $error = $response->content();
2416 $error =~ s/[\r\n]//g;
2417 $logger->error("Error initializing SmartPAY: $error");
2418 $self->ctx->{cc_configuration_error} = 1;
2424 if ($r) { return $r; }
2425 $r = $self->prepare_extended_user_info and return $r;
2427 return Apache2::Const::OK;
2430 # TODO: add other filter options as params/configs/etc.
2431 sub load_myopac_payments {
2433 my $limit = $self->cgi->param('limit') || 20;
2434 my $offset = $self->cgi->param('offset') || 0;
2435 my $e = $self->editor;
2437 $self->ctx->{payment_history_limit} = $limit;
2438 $self->ctx->{payment_history_offset} = $offset;
2441 $args->{limit} = $limit if $limit;
2442 $args->{offset} = $offset if $offset;
2444 if (my $max_age = $self->ctx->{get_org_setting}->(
2445 $e->requestor->home_ou, "opac.payment_history_age_limit"
2447 my $min_ts = DateTime->now(
2448 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2449 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2451 $logger->info("XXX min_ts: $min_ts");
2452 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2455 $self->ctx->{payments} = $U->simplereq(
2457 'open-ils.actor.user.payments.retrieve.atomic',
2458 $e->authtoken, $e->requestor->id, $args);
2460 return Apache2::Const::OK;
2463 # 1. caches the form parameters
2464 # 2. loads the credit card payment "Processing..." page
2465 sub load_myopac_pay_init {
2467 my $cache = OpenSRF::Utils::Cache->new('global');
2469 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2471 if (!@payment_xacts) {
2472 # for consistency with load_myopac_payment_form() and
2473 # to preserve backwards compatibility, if no xacts are
2474 # selected, assume all (applicable) transactions are wanted.
2475 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2476 return $stat if $stat;
2478 map { $_->{xact}->id } (
2479 @{$self->ctx->{fines}->{circulation}},
2480 @{$self->ctx->{fines}->{grocery}}
2484 return $self->generic_redirect unless @payment_xacts;
2486 my $cc_args = {"where_process" => 1};
2488 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2489 number cvv2 expire_year expire_month billing_first
2490 billing_last billing_address billing_city billing_state
2491 billing_zip stripe_payment_intent stripe_client_secret
2494 # mapping SmartPAY CGI parameters
2495 if ($self->cgi->param('Result')) {
2496 $cc_args->{smartpay_result} = $self->cgi->param('Result');
2498 if ($self->cgi->param('Secret')) {
2499 $cc_args->{smartpay_secret} = $self->cgi->param('Secret');
2501 if ($self->cgi->param('CCNumber')) {
2502 $cc_args->{number} = $self->cgi->param('CCNumber');
2506 cc_args => $cc_args,
2507 user => $self->ctx->{user}->id,
2508 xacts => \@payment_xacts
2511 # generate a temporary cache token and cache the form data
2512 my $token = md5_hex($$ . time() . rand());
2513 $cache->put_cache($token, $cache_args, 30);
2515 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2517 # after we render the processing page, we quickly redirect to submit
2518 # the actual payment. The refresh url contains the payment token.
2519 # It also contains the list of xact IDs, which allows us to clear the
2520 # cache at the earliest possible time while leaving a trace of which
2521 # transactions we were processing, so the UI can bring the user back
2522 # to the payment form w/ the same xacts if the payment fails.
2524 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2525 $refresh .= ";xact=$_" for @payment_xacts;
2526 $self->ctx->{refresh} = $refresh;
2528 return Apache2::Const::OK;
2531 # retrieve the cached CC payment info and send off for processing
2532 sub load_myopac_pay {
2534 my $token = $self->ctx->{page_args}->[0];
2535 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2537 my $cache = OpenSRF::Utils::Cache->new('global');
2538 my $cache_args = $cache->get_cache($token);
2539 $cache->delete_cache($token);
2541 # this page is loaded immediately after the token is created.
2542 # if the cached data is not there, it's because of an invalid
2543 # token (or cache failure) and not because of a timeout.
2544 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2546 my @payment_xacts = @{$cache_args->{xacts}};
2547 my $cc_args = $cache_args->{cc_args};
2549 # as an added security check, verify the user submitting
2550 # the form is the same as the user whose data was cached
2551 return Apache2::Const::HTTP_BAD_REQUEST unless
2552 $cache_args->{user} == $self->ctx->{user}->id;
2554 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2557 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2559 # balance_owed is computed specifically from the fines we're paying
2560 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2561 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2562 return Apache2::Const::HTTP_BAD_REQUEST;
2566 "cc_args" => $cc_args,
2567 "userid" => $self->ctx->{user}->id,
2568 "payment_type" => "credit_card_payment",
2569 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2572 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2573 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2576 $self->ctx->{"payment_response"} = $resp;
2578 unless ($resp->{"textcode"}) {
2579 $self->ctx->{printable_receipt} = $U->simplereq(
2580 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2581 $self->editor->authtoken, $resp->{payments}
2585 return Apache2::Const::OK;
2588 sub load_myopac_receipt_print {
2591 $self->ctx->{printable_receipt} = $U->simplereq(
2592 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2593 $self->editor->authtoken, [$self->cgi->param("payment")]
2596 return Apache2::Const::OK;
2599 sub load_myopac_receipt_email {
2602 # The following ML method doesn't actually check whether the user in
2603 # question has an email address, so we do.
2604 if ($self->ctx->{user}->email) {
2605 $self->ctx->{email_receipt_result} = $U->simplereq(
2606 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2607 $self->editor->authtoken, [$self->cgi->param("payment")]
2610 $self->ctx->{email_receipt_result} =
2611 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2614 return Apache2::Const::OK;
2618 my ($self, $limit, $offset, $id_list) = @_;
2620 # XXX TODO: check for failure after various network calls
2622 # It may be unclear, but this result structure lumps circulation and
2623 # reservation fines together, and keeps grocery fines separate.
2624 $self->ctx->{"fines"} = {
2625 "circulation" => [],
2632 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2634 # TODO: This should really be a ML call, but the existing calls
2635 # return an excessive amount of data and don't offer streaming
2637 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2639 my $req = $cstore->request(
2640 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2642 usr => $self->editor->requestor->id,
2643 balance_owed => {'!=' => 0},
2644 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2649 mobts => [qw/grocery circulation reservation/],
2650 bresv => ['target_resource_type'],
2654 circ => ['target_copy'],
2655 acp => ['call_number'],
2658 order_by => { mobts => 'xact_start' },
2663 # Collect $$ amounts from each transaction for summing below.
2664 my (@paid_amounts, @owed_amounts, @balance_amounts);
2666 while(my $resp = $req->recv) {
2667 my $mobts = $resp->content;
2668 my $circ = $mobts->circulation;
2671 if($mobts->grocery) {
2672 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2673 $last_billing = pop(@billings);
2676 push(@paid_amounts, $mobts->total_paid);
2677 push(@owed_amounts, $mobts->total_owed);
2678 push(@balance_amounts, $mobts->balance_owed);
2680 my $marc_xml = undef;
2681 if ($mobts->xact_type eq 'reservation' and
2682 $mobts->reservation->target_resource_type->record) {
2683 $marc_xml = XML::LibXML->new->parse_string(
2684 $mobts->reservation->target_resource_type->record->marc
2686 } elsif ($mobts->xact_type eq 'circulation' and
2687 $circ->target_copy->call_number->id != -1) {
2688 $marc_xml = XML::LibXML->new->parse_string(
2689 $circ->target_copy->call_number->record->marc
2694 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2697 last_grocery_billing => $last_billing,
2698 marc_xml => $marc_xml
2705 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2706 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2707 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2712 sub prepare_fines_for_payment {
2713 # This assumes $self->prepare_fines has already been run
2717 if ($self->ctx->{fines}) {
2718 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2719 @{$self->ctx->{fines}->{circulation}},
2720 @{$self->ctx->{fines}->{grocery}}
2727 sub load_myopac_main {
2729 my $limit = $self->cgi->param('limit') || 0;
2730 my $offset = $self->cgi->param('offset') || 0;
2731 $self->ctx->{search_ou} = $self->_get_search_lib();
2732 $self->ctx->{user}->notes(
2733 $self->editor->search_actor_usr_message({
2734 usr => $self->ctx->{user}->id,
2738 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2741 sub load_myopac_update_email {
2743 my $e = $self->editor;
2744 my $ctx = $self->ctx;
2745 my $email = $self->cgi->param('email') || '';
2746 my $current_pw = $self->cgi->param('current_pw') || '';
2748 # needed for most up-to-date email address
2749 if (my $r = $self->prepare_extended_user_info) { return $r };
2751 return Apache2::Const::OK
2752 unless $self->cgi->request_method eq 'POST';
2754 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2755 $ctx->{invalid_email} = $email;
2756 return Apache2::Const::OK;
2759 my $stat = $U->simplereq(
2761 'open-ils.actor.user.email.update',
2762 $e->authtoken, $email, $current_pw);
2764 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2765 $ctx->{password_incorrect} = 1;
2766 return Apache2::Const::OK;
2769 unless ($self->cgi->param("redirect_to")) {
2770 my $url = $self->apache->unparsed_uri;
2771 $url =~ s/update_email/prefs/;
2773 return $self->generic_redirect($url);
2776 return $self->generic_redirect;
2779 sub load_myopac_update_username {
2781 my $e = $self->editor;
2782 my $ctx = $self->ctx;
2783 my $username = $self->cgi->param('username') || '';
2784 my $current_pw = $self->cgi->param('current_pw') || '';
2786 $self->prepare_extended_user_info;
2788 my $allow_change = 1;
2790 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2791 if(defined($lock_usernames) and $lock_usernames == 1) {
2792 # Policy says no username changes
2795 # We want this further down.
2796 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2797 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2798 if(!$username_unlimit) {
2800 # Default is "starts with a number"
2801 $regex_check = '^\d+';
2803 # You already have a username?
2804 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2809 if(!$allow_change) {
2810 my $url = $self->apache->unparsed_uri;
2811 $url =~ s/update_username/prefs/;
2813 return $self->generic_redirect($url);
2816 return Apache2::Const::OK
2817 unless $self->cgi->request_method eq 'POST';
2819 unless($username and $username !~ /\s/) { # any other username restrictions?
2820 $ctx->{invalid_username} = $username;
2821 return Apache2::Const::OK;
2824 # New username can't look like a barcode if we have a barcode regex
2825 if($regex_check and $username =~ /$regex_check/) {
2826 $ctx->{invalid_username} = $username;
2827 return Apache2::Const::OK;
2830 # New username has to look like a username if we have a username regex
2831 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2832 if($regex_check and $username !~ /$regex_check/) {
2833 $ctx->{invalid_username} = $username;
2834 return Apache2::Const::OK;
2837 if($username ne $e->requestor->usrname) {
2839 my $evt = $U->simplereq(
2841 'open-ils.actor.user.username.update',
2842 $e->authtoken, $username, $current_pw);
2844 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2845 $ctx->{password_incorrect} = 1;
2846 return Apache2::Const::OK;
2849 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2850 $ctx->{username_exists} = $username;
2851 return Apache2::Const::OK;
2855 my $url = $self->apache->unparsed_uri;
2856 $url =~ s/update_username/prefs/;
2858 return $self->generic_redirect($url);
2861 sub load_myopac_update_locale {
2863 my $e = $self->editor;
2864 my $ctx = $self->ctx;
2865 my $lang = $self->cgi->param('pref_lang') || '';
2866 my $current_pw = $self->cgi->param('current_pw') || '';
2868 $self->prepare_extended_user_info;
2870 my $locs = $U->simplereq(
2872 "open-ils.cstore.direct.config.i18n_locale.search.atomic",
2873 { "code" => { "!=" => undef } }
2877 foreach my $l (@$locs) { $user_locales{$l->code} = $l->name; }
2878 $self->ctx->{i18n_locales} = \%user_locales;
2880 return Apache2::Const::OK
2881 unless $self->cgi->request_method eq 'POST';
2883 if($lang ne $e->requestor->locale) {
2884 my $evt = $U->simplereq(
2886 'open-ils.actor.user.locale.update',
2887 $e->authtoken, $lang, $current_pw);
2889 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2890 $ctx->{password_incorrect} = 1;
2891 return Apache2::Const::OK;
2895 my $url = $self->apache->unparsed_uri;
2896 $url =~ s/update_locale/prefs/;
2898 return $self->generic_redirect($url);
2901 sub load_myopac_update_password {
2903 my $e = $self->editor;
2904 my $ctx = $self->ctx;
2906 return Apache2::Const::OK
2907 unless $self->cgi->request_method eq 'POST';
2909 my $current_pw = $self->cgi->param('current_pw') || '';
2910 my $new_pw = $self->cgi->param('new_pw') || '';
2911 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2913 unless($new_pw eq $new_pw2) {
2914 $ctx->{password_nomatch} = 1;
2915 return Apache2::Const::OK;
2918 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2921 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2922 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2925 if($pw_regex and $new_pw !~ /$pw_regex/) {
2926 $ctx->{password_invalid} = 1;
2927 return Apache2::Const::OK;
2930 my $evt = $U->simplereq(
2932 'open-ils.actor.user.password.update',
2933 $e->authtoken, $new_pw, $current_pw);
2936 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2937 $ctx->{password_incorrect} = 1;
2938 return Apache2::Const::OK;
2941 my $url = $self->apache->unparsed_uri;
2942 $url =~ s/update_password/prefs/;
2944 return $self->generic_redirect($url);
2947 sub _update_bookbag_metadata {
2948 my ($self, $bookbag) = @_;
2950 $bookbag->name($self->cgi->param("name"));
2951 $bookbag->description($self->cgi->param("description"));
2953 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2957 sub _get_lists_per_page {
2960 if($self->editor->requestor) {
2961 $self->timelog("Checking for opac.lists_per_page preference");
2962 # See if the user has a lists per page preference
2963 my $ipp = $self->editor->search_actor_user_setting({
2964 usr => $self->editor->requestor->id,
2965 name => 'opac.lists_per_page'
2967 $self->timelog("Got opac.lists_per_page preference");
2968 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2970 return 10; # default
2973 sub _get_items_per_page {
2976 if($self->editor->requestor) {
2977 $self->timelog("Checking for opac.list_items_per_page preference");
2978 # See if the user has a list items per page preference
2979 my $ipp = $self->editor->search_actor_user_setting({
2980 usr => $self->editor->requestor->id,
2981 name => 'opac.list_items_per_page'
2983 $self->timelog("Got opac.list_items_per_page preference");
2984 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2986 return 10; # default
2989 sub load_myopac_bookbags {
2991 my $e = $self->editor;
2992 my $ctx = $self->ctx;
2993 my $limit = $self->_get_lists_per_page || 10;
2994 my $offset = $self->cgi->param('offset') || 0;
2996 $ctx->{bookbags_limit} = $limit;
2997 $ctx->{bookbags_offset} = $offset;
2999 # for list item pagination
3000 my $item_limit = $self->_get_items_per_page;
3001 my $item_page = $self->cgi->param('item_page') || 1;
3002 my $item_offset = ($item_page - 1) * $item_limit;
3003 $ctx->{bookbags_item_page} = $item_page;
3005 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3006 $e->xact_begin; # replication...
3008 my $rv = $self->load_mylist;
3009 unless($rv eq Apache2::Const::OK) {
3014 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
3016 {owner => $e->requestor->id, btype => 'bookbag'}, {
3017 order_by => {cbreb => 'name'},
3025 if(!$ctx->{bookbags}) {
3027 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3030 # We load the user prefs to get their default bookbag.
3031 $self->_load_user_with_prefs;
3033 # We also want a total count of the user's bookbags.
3035 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
3037 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
3039 my $r = $e->json_query($q);
3040 $ctx->{bookbag_count} = $r->[0]->{'count'};
3042 # If the user wants a specific bookbag's items, load them.
3044 if ($self->cgi->param("bbid")) {
3046 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
3049 my $query = $self->_prepare_bookbag_container_query(
3050 $bookbag->id, $sorter, $modifier
3053 # Calculate total count of the items in selected bookbag.
3054 # This total includes record entries that have no assets available.
3055 my $bb_search_results = $U->simplereq(
3056 "open-ils.search", "open-ils.search.biblio.multiclass.query",
3057 {"limit" => 1, "offset" => 0}, $query
3058 ); # we only need the count, so do the actual search with limit=1
3060 if ($bb_search_results) {
3061 $ctx->{bb_item_count} = $bb_search_results->{count};
3063 $logger->warn("search failed in load_myopac_bookbags()");
3064 $ctx->{bb_item_count} = 0; # fallback value
3067 #calculate page count
3068 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
3070 if ( ($self->cgi->param("action") || '') eq "editmeta") {
3071 if (!$self->_update_bookbag_metadata($bookbag)) {
3073 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3076 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
3079 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
3080 if ($self->cgi->param($param)) {
3081 my @vals = $self->cgi->param($param);
3082 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3086 return $self->generic_redirect($url);
3090 # we're done with our CStoreEditor. Rollback here so
3091 # later calls don't cause a timeout, resulting in a
3092 # transaction rollback under the covers.
3096 # For list items pagination
3098 "limit" => $item_limit,
3099 "offset" => $item_offset
3102 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
3103 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3105 # capture pref_ou for callnumber filter/display
3106 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
3108 # search for local callnumbers for display
3109 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
3111 my (undef, @recs) = $self->get_records_and_facets(
3112 [ map {$_->target_biblio_record_entry->id} @$items ],
3115 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
3117 site => $ctx->{get_aou}->($focus_ou)->shortname,
3118 pref_lib => $ctx->{pref_ou}
3122 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
3124 $bookbag->items($items);
3128 # If we have add_rec, we got here from the "Add to new list"
3129 # or "See all" popmenu items.
3130 if (my $add_rec = $self->cgi->param('add_rec')) {
3131 $self->ctx->{add_rec} = $add_rec;
3132 # But not in the staff client, 'cause that breaks things.
3133 unless ($self->ctx->{is_staff}) {
3134 # allow caller to provide the where_from in cases where
3135 # the referer is an intermediate error page
3136 if ($self->cgi->param('where_from')) {
3137 $self->ctx->{where_from} = $self->cgi->param('where_from');
3139 $self->ctx->{where_from} = $self->ctx->{referer};
3140 if ( my $anchor = $self->cgi->param('anchor') ) {
3141 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3147 # this rollback may be a dupe, but that's OK because
3148 # cstoreditor ignores dupe rollbacks
3151 return Apache2::Const::OK;
3155 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3156 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3157 sub load_myopac_bookbag_update {
3158 my ($self, $action, $list_id, @hold_recs) = @_;
3159 my $e = $self->editor;
3160 my $cgi = $self->cgi;
3162 # save_notes is effectively another action, but is passed in a separate
3163 # CGI parameter for what are really just layout reasons.
3164 $action = 'save_notes' if $cgi->param('save_notes');
3165 $action ||= $cgi->param('action');
3167 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3169 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3170 my @selected_item = $cgi->param('selected_item');
3171 my $shared = $cgi->param('shared');
3172 my $move_cart = $cgi->param('move_cart');
3173 my $name = $cgi->param('name');
3174 my $description = $cgi->param('description');
3178 # bail out if user is attempting an action that requires
3179 # that at least one list item be selected
3180 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3181 ($action eq 'place_hold' || $action eq 'print' ||
3182 $action eq 'email' || $action eq 'del_item')) {
3183 my $url = $self->ctx->{referer};
3184 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3185 return $self->generic_redirect($url);
3188 # This url intentionally leaves off the edit_notes parameter, but
3189 # may need to add some back in for paging.
3191 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3192 $self->ctx->{opac_root} . "/myopac/lists?";
3194 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3195 if ($cgi->param($param)) {
3196 my @vals = $cgi->param($param);
3197 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3201 if ($action eq 'create') {
3204 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3206 $list->description($description);
3207 $list->owner($e->requestor->id);
3208 $list->btype('bookbag');
3209 $list->pub($shared ? 't' : 'f');
3210 $success = $U->simplereq('open-ils.actor',
3211 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3212 if (ref($success) ne 'HASH') {
3213 $list_id = (ref($success)) ? $success->id : $success;
3214 if (scalar @add_rec) {
3215 foreach my $add_rec (@add_rec) {
3216 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3217 $item->bucket($list_id);
3218 $item->target_biblio_record_entry($add_rec);
3219 $success = $U->simplereq('open-ils.actor',
3220 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3221 last unless $success;
3225 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3226 foreach my $add_rec (@$list) {
3227 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3228 $item->bucket($list_id);
3229 $item->target_biblio_record_entry($add_rec);
3230 $success = $U->simplereq('open-ils.actor',
3231 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3232 last unless $success;
3234 $self->clear_anon_cache;
3237 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3240 $self->ctx->{bucket_failure_noname} = 1;
3243 } elsif($action eq 'place_hold') {
3245 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3246 my $from_basket = scalar(@hold_recs);
3247 unless (@hold_recs) {
3248 if (@selected_item) {
3249 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3250 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3254 return Apache2::Const::OK unless @hold_recs;
3255 $logger->info("placing holds from list page on: @hold_recs");
3257 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3258 $url .= ';hold_target=' . $_ for @hold_recs;
3259 $url .= ';from_basket=1' if $from_basket;
3260 foreach my $param (('loc', 'qtype', 'query')) {
3261 if ($cgi->param($param)) {
3262 my @vals = $cgi->param($param);
3263 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3266 return $self->generic_redirect($url);
3268 } elsif ($action eq 'print') {
3269 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3270 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3271 if (!$incoming_sort) {
3272 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3274 if (!$incoming_sort) {
3275 $incoming_sort = 'author';
3278 $incoming_sort =~ s/sort.*$//;
3280 $self->ctx->{sort} = $incoming_sort;
3281 $self->ctx->{sort_dir} = $sort_dir;
3283 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3284 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3285 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3286 return $self->load_mylist_print($temp_cache_key);
3287 } elsif ($action eq 'email') {
3288 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3289 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3290 if (!$incoming_sort) {
3291 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3293 if (!$incoming_sort) {
3294 $incoming_sort = 'author';
3297 $incoming_sort =~ s/sort.*$//;
3299 $self->ctx->{sort} = $incoming_sort;
3300 $self->ctx->{sort_dir} = $sort_dir;
3302 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3303 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3304 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3305 return $self->load_mylist_email($temp_cache_key);
3308 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3310 return Apache2::Const::HTTP_BAD_REQUEST unless
3311 $list and $list->owner == $e->requestor->id;
3314 if($action eq 'delete') {
3315 $success = $U->simplereq('open-ils.actor',
3316 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3318 # We check to see if we're deleting the user's default list.
3319 $self->_load_user_with_prefs;
3320 my $settings_map = $self->ctx->{user_setting_map};
3321 if ($$settings_map{'opac.default_list'} == $list_id) {
3322 # We unset the user's opac.default_list setting.
3323 $success = $U->simplereq(
3325 'open-ils.actor.patron.settings.update',
3328 { 'opac.default_list' => 0 }
3332 } elsif($action eq 'show') {
3333 unless($U->is_true($list->pub)) {
3335 $success = $U->simplereq('open-ils.actor',
3336 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3339 } elsif($action eq 'hide') {
3340 if($U->is_true($list->pub)) {
3342 $success = $U->simplereq('open-ils.actor',
3343 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3346 } elsif($action eq 'rename') {
3349 $success = $U->simplereq('open-ils.actor',
3350 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3353 } elsif($action eq 'add_rec') {
3354 foreach my $add_rec (@add_rec) {
3355 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3356 $item->bucket($list_id);
3357 $item->target_biblio_record_entry($add_rec);
3358 $success = $U->simplereq('open-ils.actor',
3359 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3360 last unless $success;
3362 # Redirect back where we came from if we have an anchor parameter:
3363 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3364 $url = $self->ctx->{referer};
3365 $url =~ s/#.*|$/#$anchor/;
3366 } elsif ($cgi->param('where_from')) {
3367 # Or, if we have a "where_from" parameter.
3368 $url = $cgi->param('where_from');
3370 } elsif ($action eq 'del_item') {
3371 foreach (@selected_item) {
3372 $success = $U->simplereq(
3374 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3376 last unless $success;
3378 } elsif ($action eq 'save_notes') {
3379 $success = $self->update_bookbag_item_notes;
3380 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3381 } elsif ($action eq 'make_default') {
3382 $success = $U->simplereq(
3384 'open-ils.actor.patron.settings.update',
3387 { 'opac.default_list' => $list_id }
3389 } elsif ($action eq 'remove_default') {
3390 $success = $U->simplereq(
3392 'open-ils.actor.patron.settings.update',
3395 { 'opac.default_list' => 0 }
3399 return $self->generic_redirect($url) if $success;
3401 $self->ctx->{where_from} = $cgi->param('where_from');
3402 $self->ctx->{bucket_action} = $action;
3403 $self->ctx->{bucket_action_failed} = 1;
3404 return Apache2::Const::OK;
3407 sub update_bookbag_item_notes {
3409 my $e = $self->editor;
3411 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3412 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3414 # We're going to leverage an API call that's already been written to check
3415 # permissions appropriately.
3417 my $a = create OpenSRF::AppSession("open-ils.actor");
3418 my $method = "open-ils.actor.container.item_note.cud";
3420 for my $note_key (@note_keys) {
3423 my $id = ($note_key =~ /(\d+)/)[0];
3426 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3427 my $event = $e->die_event;
3428 $self->apache->log->warn(
3429 "error retrieving cbrebin id $id, got event " .
3433 $self->ctx->{bucket_action_event} = $event;
3437 if (length($self->cgi->param($note_key))) {
3438 $note->ischanged(1);
3439 $note->note($self->cgi->param($note_key));
3441 $note->isdeleted(1);
3444 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3446 if (defined $U->event_code($r)) {
3447 $self->apache->log->warn(
3448 "attempt to modify cbrebin " . $note->id .
3449 " returned event " . $r->{textcode}
3453 $self->ctx->{bucket_action_event} = $r;
3458 for my $item_key (@item_keys) {
3459 my $id = int(($item_key =~ /(\d+)/)[0]);
3460 my $text = $self->cgi->param($item_key);
3463 next unless length $text;
3465 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3470 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3472 if (defined $U->event_code($r)) {
3473 $self->apache->log->warn(
3474 "attempt to create cbrebin for item " . $note->item .
3475 " returned event " . $r->{textcode}
3479 $self->ctx->{bucket_action_event} = $r;
3488 sub load_myopac_bookbag_print {
3491 my $id = int($self->cgi->param("list"));
3493 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3496 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3500 # Get the bookbag object itself, assuming we're allowed to.
3501 if ($self->editor->allowed("VIEW_CONTAINER")) {
3503 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3505 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3509 "owner" => $self->editor->requestor->id,
3513 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3515 $bbag = pop @$bookbags;
3518 # If we have a bookbag we're allowed to look at, issue the A/T event
3519 # to get CSV, passing as a user param that search query we built before.
3521 $self->ctx->{csv} = $U->fire_object_event(
3522 undef, "container.biblio_record_entry_bucket.csv",
3523 $bbag, $self->editor->requestor->home_ou,
3524 undef, {"item_search" => $item_search}
3528 # Create a reasonable filename and set the content disposition to
3529 # provoke browser download dialogs.
3530 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3532 return $self->set_file_download_headers("$filename.csv");
3535 sub load_myopac_circ_history_export {
3537 my $e = $self->editor;
3538 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3540 my $circs = $self->fetch_user_circ_history(1);
3542 $self->ctx->{csv}->{circs} = $circs;
3543 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3547 sub load_myopac_reservations {
3549 my $e = $self->editor;
3550 my $ctx = $self->ctx;
3552 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3553 $e->authtoken, undef
3556 $ctx->{reservations} = $upcoming;
3557 return Apache2::Const::OK;
3561 sub load_password_reset {
3563 my $cgi = $self->cgi;
3564 my $ctx = $self->ctx;
3565 my $barcode = $cgi->param('barcode');
3566 my $username = $cgi->param('username');
3567 my $email = $cgi->param('email');
3568 my $pwd1 = $cgi->param('pwd1');
3569 my $pwd2 = $cgi->param('pwd2');
3570 my $uuid = $ctx->{page_args}->[0];
3574 $logger->info("patron password reset with uuid $uuid");
3576 if ($pwd1 and $pwd2) {
3578 if ($pwd1 eq $pwd2) {
3580 my $response = $U->simplereq(
3582 'open-ils.actor.patron.password_reset.commit',
3585 $logger->info("patron password reset response " . Dumper($response));
3587 if ($U->event_code($response)) { # non-success event
3589 my $code = $response->{textcode};
3591 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3592 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3595 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3596 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3601 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3604 } else { # passwords not equal
3606 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3609 } else { # 2 password values needed
3611 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3614 } elsif ($barcode or $username) {
3616 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3617 push(@params, $email) if $email;
3621 'open-ils.actor.patron.password_reset.request', @params);
3623 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3626 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3627 return Apache2::Const::OK;