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 normally OK, but if the record has
1626 # no non-part copies, the hold will ultimately fail. When that happens,
1627 # require the user to select a part.
1629 # If the global flag circ.holds.api_require_monographic_part_when_present is
1630 # enabled, or the library setting circ.holds.ui_require_monographic_part_when_present
1631 # is active for any item owning library associated with the bib, then any configured
1632 # parts for the bib is enough to disallow title holds (aka require part selection).
1633 my $part_required = 0;
1635 $part_required = $ctx->{part_required_when_present_global_flag};
1636 if (!$part_required) {
1637 my $resp = $e->json_query({
1639 acn => ['owning_lib']
1641 from => {acn => {acp => {type => 'left'}}},
1646 {id => undef} # left join
1649 '+acn' => {deleted => 'f', record => $rec->id}
1653 my $org_ids = [map {$_->{owning_lib}} @$resp];
1654 foreach my $org (@$org_ids) { # FIXME: worth shortcutting/optimizing?
1655 if ($self->ctx->{get_org_setting}->($org, 'circ.holds.ui_require_monographic_part_when_present')) {
1660 if (!$part_required) {
1661 my $np_copies = $e->json_query({
1662 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1663 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1665 '+acp' => {deleted => 'f'},
1666 '+acn' => {deleted => 'f', record => $rec->id},
1667 '+acpm' => {id => undef}
1670 $part_required = 1 if $np_copies->[0]->{count} == 0;
1674 push(@hold_data, $data_filler->({
1678 part_required => $part_required
1683 my $vols = $e->batch_retrieve_asset_call_number([
1686 "flesh_fields" => {"acn" => ["record"]}
1688 ], {substream => 1});
1690 for my $id (@targets) {
1691 my ($vol) = grep {$_->id eq $id} @$vols;
1692 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1696 my $copies = $e->batch_retrieve_asset_copy([
1700 "acn" => ["record"],
1701 "acp" => ["call_number"]
1704 ], {substream => 1});
1706 for my $id (@targets) {
1707 my ($copy) = grep {$_->id eq $id} @$copies;
1708 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1712 my $isses = $e->batch_retrieve_serial_issuance([
1716 "siss" => ["subscription"], "ssub" => ["record_entry"]
1719 ], {substream => 1});
1721 for my $id (@targets) {
1722 my ($iss) = grep {$_->id eq $id} @$isses;
1723 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1728 }->{$ctx->{hold_type}}->();
1730 # caller sent bad target IDs or the wrong hold type
1731 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1733 # generate the MARC xml for each record
1734 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1736 my $pickup_lib = $cgi->param('pickup_lib');
1737 # no pickup lib means no holds placement, except for subscriptions
1738 return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1740 $ctx->{hold_attempt_made} = 1;
1742 # Give the original CGI params back to the user in case they
1743 # want to try to override something.
1744 $ctx->{orig_params} = $cgi->Vars;
1745 delete $ctx->{orig_params}{submit};
1746 delete $ctx->{orig_params}{hold_target};
1747 delete $ctx->{orig_params}{part};
1749 my $usr = $e->requestor->id;
1751 if ($ctx->{is_staff}) {
1752 $logger->info("Staff initiated hold");
1753 if (!$cgi->param("hold_usr_is_requestor")) {
1754 # find the real hold target
1756 $usr = $U->simplereq(
1758 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1759 $e->authtoken, $cgi->param("hold_usr"));
1761 if (defined $U->event_code($usr)) {
1762 $ctx->{hold_failed} = 1;
1763 $ctx->{hold_failed_event} = $usr;
1767 if ($ctx->{hold_subscription}) {
1768 # this is a batch event, hold "user" is a bucket id
1769 $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1770 $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1774 # target_id is the true target_id for holds placement.
1775 # needed for attempt_hold_placement()
1776 # With the exception of P-type holds, target_id == target->id.
1777 $_->{target_id} = $_->{target}->id for @hold_data;
1779 if ($ctx->{hold_type} eq 'T') {
1781 # Much like quantum wave-particles, P-type holds pop into
1782 # and out of existence at the user's whim. For our purposes,
1783 # we treat such holds as T(itle) holds with a selected_part
1784 # designation. When the time comes to pass the hold information
1785 # off for holds possibility testing and placement, make it look
1786 # like a real P-type hold.
1787 my (@p_holds, @t_holds);
1789 # Now that we have the num_copies field for mutliple title and
1790 # metarecord hold placement, the number of holds and parts
1791 # arrays can get out of sync. We only want to parse out parts
1792 # if the numbers are equal.
1793 if ($#hold_data == $#parts) {
1794 for my $idx (0..$#parts) {
1795 my $hdata = $hold_data[$idx];
1796 if (my $part = $parts[$idx]) {
1797 $hdata->{target_id} = $part;
1798 $hdata->{selected_part} = $part;
1799 push(@p_holds, $hdata);
1801 push(@t_holds, $hdata);
1805 @t_holds = @hold_data;
1808 $self->apache->log->warn("$#parts : @t_holds");
1810 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1811 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1814 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1817 # NOTE: we are leaving the staff-placed patron barcode cookie
1818 # in place. Otherwise, it's not possible to place more than
1819 # one hold for the patron within a staff/patron session. This
1820 # does leave the barcode to linger longer than is ideal, but
1821 # normal staff work flow will cause the cookie to be replaced
1822 # with each new patron anyway.
1823 # TODO: See about getting the staff client to clear the cookie
1825 # return to the place_hold page so the results of the hold
1826 # placement attempt can be reported to the user
1827 return Apache2::Const::OK;
1830 sub attempt_hold_placement {
1831 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1832 my $cgi = $self->cgi;
1833 my $ctx = $self->ctx;
1834 my $e = $self->editor;
1836 my $user_container = undef;
1837 if (ref($usr)) { # $usr is actually a container for a subscription...
1838 $user_container = $usr->id;
1839 return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1842 # First see if we should warn/block for any holds that
1843 # might have locally available items for non-subscriptions.
1844 if (!$user_container) {
1845 for my $hdata (@hold_data) {
1846 my ($local_block, $local_alert) = $self->local_avail_concern(
1847 $hdata->{target_id}, $hold_type, $pickup_lib);
1850 $hdata->{hold_failed} = 1;
1851 $hdata->{hold_local_block} = 1;
1852 } elsif ($local_alert) {
1853 $hdata->{hold_failed} = 1;
1854 $hdata->{hold_local_alert} = 1;
1859 my $method = $user_container
1860 ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1861 : 'open-ils.circ.holds.test_and_create.batch';
1863 if ($cgi->param('override')) {
1864 $method .= '.override';
1866 } elsif (!$ctx->{is_staff}) {
1868 $method .= '.override' if $self->ctx->{get_org_setting}->(
1869 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1872 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1875 if(@create_targets) {
1877 # holdable formats may be different for each MR hold.
1878 # map each set to the ID of the target.
1879 my $holdable_formats = {};
1880 if ($hold_type eq 'M') {
1881 $holdable_formats->{$_->{target_id}} =
1882 $_->{holdable_formats} for @hold_data;
1885 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1887 my @create_params = ();
1889 if ($user_container) {
1892 hold_type => $hold_type,
1893 holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1902 pickup_lib => $pickup_lib,
1903 hold_type => $hold_type,
1904 holdable_formats_map => $holdable_formats,
1910 my $breq = $bses->request($method, $e->authtoken, @create_params);
1912 while (my $resp = $breq->recv) {
1914 $resp = $resp->content;
1915 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1917 if ($U->event_code($resp)) {
1918 $ctx->{general_hold_error} = $resp;
1922 # subscription batch create sends an initial response to assist with client-side counting
1925 defined($$resp{count}) and $$resp{count} == 0
1926 and defined($$resp{total}) and $$resp{total} > 0
1929 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1930 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1931 my $result = $resp->{result};
1933 if ($U->event_code($result)) {
1934 # e.g. permission denied
1935 $hdata->{hold_failed} = 1;
1936 $hdata->{hold_failed_event} = $result;
1940 if(not ref $result and $result > 0) {
1941 # successul hold returns the hold ID
1942 $hdata->{hold_success} = $result;
1945 # hold-specific failure event
1946 $hdata->{hold_failed} = 1;
1948 if (ref $result eq 'HASH') {
1949 $hdata->{hold_failed_event} = $result->{last_event};
1951 if ($result->{age_protected_copy}) {
1952 my %temp = %{$hdata->{hold_failed_event}};
1953 my $theTextcode = $temp{"textcode"};
1954 $theTextcode.=".override";
1955 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1956 $hdata->{age_protect} = 1;
1958 $hdata->{could_override} = $result->{place_unfillable} ||
1959 $self->test_could_override($hdata->{hold_failed_event});
1961 } elsif (ref $result eq 'ARRAY') {
1962 $hdata->{hold_failed_event} = $result->[0];
1964 if ($result->[3]) { # age_protect_only
1965 my %temp = %{$hdata->{hold_failed_event}};
1966 my $theTextcode = $temp{"textcode"};
1967 $theTextcode.=".override";
1968 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1969 $hdata->{age_protect} = 1;
1971 $hdata->{could_override} = $result->[4] || # place_unfillable
1972 $self->test_could_override($hdata->{hold_failed_event});
1982 if ($self->cgi->param('clear_cart')) {
1983 $self->clear_anon_cache;
1987 # pull the selected formats and languages for metarecord holds
1988 # from the CGI params and map them into the JSON holdable
1989 # formats...er, format.
1990 # if no metarecord is provided, we'll pull it from the target
1991 # of the provided hold.
1992 sub compile_holdable_formats {
1993 my ($self, $mr_id, $hold_id) = @_;
1994 my $e = $self->editor;
1995 my $cgi = $self->cgi;
1997 # exit early if not needed
1999 grep /metarecord_formats_|metarecord_langs_/,
2002 # CGI params are based on the MR id, since during hold placement
2003 # we have no old ID. During hold edit, map the hold ID back to
2004 # the metarecod target.
2006 $e->retrieve_action_hold_request($hold_id)->target
2009 my $format_attr = $self->ctx->{get_cgf}->(
2010 'opac.metarecord.holds.format_attr');
2012 if (!$format_attr) {
2013 $logger->error("Missing config.global_flag: ".
2014 "opac.metarecord.holds.format_attr!");
2018 $format_attr = $format_attr->value;
2020 # during hold placement or edit submission, the user selects
2021 # which of the available formats/langs are acceptable.
2022 # Capture those here as the holdable_formats for the MR hold.
2023 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
2024 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
2026 # map the selected attrs into the JSON holdable_formats structure
2028 if (@selected_formats) {
2030 map { {_attr => $format_attr, _val => $_} }
2034 if (@selected_langs) {
2036 map { {_attr => 'item_lang', _val => $_} }
2041 return OpenSRF::Utils::JSON->perl2JSON($blob);
2044 sub fetch_user_circs {
2046 my $flesh = shift; # flesh bib data, etc.
2047 my $circ_ids = shift;
2051 my $e = $self->editor;
2056 @circ_ids = @$circ_ids;
2061 select => {circ => ['id']},
2065 usr => $e->requestor->id,
2066 checkin_time => undef,
2068 {stop_fines => undef},
2069 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2073 order_by => {circ => ['due_date']}
2076 $query->{limit} = $limit if $limit;
2077 $query->{offset} = $offset if $offset;
2079 my $ids = $e->json_query($query);
2080 @circ_ids = map {$_->{id}} @$ids;
2083 return [] unless @circ_ids;
2088 circ => ['target_copy'],
2089 acp => ['call_number','parts'],
2090 acn => ['record','owning_lib','prefix','suffix']
2095 my $circs = $e->search_action_circulation(
2096 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2099 for my $circ (@$circs) {
2102 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2103 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2104 undef # pre-cat copy, use the dummy title/author instead
2109 # make sure the final list is in the correct order
2111 for my $id (@circ_ids) {
2114 (grep { $_->{circ}->id == $id } @circs)
2118 return \@sorted_circs;
2122 sub handle_circ_renew {
2125 my $ctx = $self->ctx;
2127 my @renew_ids = $self->cgi->param('circ');
2129 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2131 # TODO: fire off renewal calls in batches to speed things up
2133 for my $circ (@$circs) {
2135 my $evt = $U->simplereq(
2137 'open-ils.circ.renew',
2138 $self->editor->authtoken,
2140 patron_id => $self->editor->requestor->id,
2141 copy_id => $circ->{circ}->target_copy,
2146 # TODO return these, then insert them into the circ data
2147 # blob that is shoved into the template for each circ
2148 # so the template won't have to match them
2149 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2155 sub load_myopac_circs {
2157 my $e = $self->editor;
2158 my $ctx = $self->ctx;
2161 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2162 my $offset = $self->cgi->param('offset') || 0;
2163 my $action = $self->cgi->param('action') || '';
2165 # perform the renewal first if necessary
2166 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2168 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2170 my $success_renewals = 0;
2171 my $failed_renewals = 0;
2172 for my $data (@{$ctx->{circs}}) {
2173 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2176 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2178 # extract the fail_part, if present, from the event payload;
2179 # since # the payload is an acp object in some cases,
2180 # blindly looking for a # 'fail_part' key in the template can
2182 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2183 $evt->{payload}->{fail_part} :
2186 $data->{renewal_response} = $evt;
2187 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2188 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2192 $ctx->{success_renewals} = $success_renewals;
2193 $ctx->{failed_renewals} = $failed_renewals;
2195 return Apache2::Const::OK;
2198 sub load_myopac_circ_history {
2200 my $e = $self->editor;
2201 my $ctx = $self->ctx;
2202 my $limit = $self->cgi->param('limit') || 15;
2203 my $offset = $self->cgi->param('offset') || 0;
2204 my $action = $self->cgi->param('action') || '';
2206 my $circ_handle_result;
2207 $circ_handle_result = $self->handle_circ_update($action) if $action;
2209 $ctx->{circ_history_limit} = $limit;
2210 $ctx->{circ_history_offset} = $offset;
2212 # Defer limitation to circ_history.tt2 when sorting
2213 if ($self->cgi->param('sort')) {
2218 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2219 return Apache2::Const::OK;
2222 # if 'flesh' is set, copy data etc. is loaded and the return value is
2223 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2225 sub fetch_user_circ_history {
2226 my ($self, $flesh, $limit, $offset) = @_;
2227 my $e = $self->editor;
2230 $limits{offset} = $offset if defined $offset;
2231 $limits{limit} = $limit if defined $limit;
2236 auch => ['target_copy','source_circ'],
2237 acp => ['call_number','parts'],
2238 acn => ['record','prefix','suffix']
2243 my $circs = $e->search_action_user_circ_history(
2245 {usr => $e->requestor->id},
2246 { # order newest to oldest by default
2247 order_by => {auch => 'xact_start DESC'},
2248 $flesh ? %flesh_ops : (),
2256 return $circs unless $flesh;
2260 my %unapi_cache = ();
2261 for my $circ (@$circs) {
2262 if ($circ->target_copy->call_number->id == -1) {
2265 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2269 my $bre_id = $circ->target_copy->call_number->record->id;
2271 if (exists $unapi_cache{$bre_id}) {
2272 $unapi = $unapi_cache{$bre_id};
2274 my $result = $e->json_query({
2276 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2280 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2291 marc_xml => undef # failed, but try to go on
2300 sub handle_circ_update {
2303 my $circ_ids = shift;
2305 $circ_ids //= [$self->cgi->param('circ_id')];
2307 if ($action =~ /delete/) {
2309 circ_ids => $circ_ids,
2314 'open-ils.actor.history.circ.clear',
2315 $self->editor->authtoken,
2323 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2324 sub load_myopac_hold_history {
2326 my $e = $self->editor;
2327 my $ctx = $self->ctx;
2328 my $limit = $self->cgi->param('limit') || 15;
2329 my $offset = $self->cgi->param('offset') || 0;
2330 $ctx->{hold_history_limit} = $limit;
2331 $ctx->{hold_history_offset} = $offset;
2333 my $hold_ids = $e->json_query({
2337 transform => 'action.usr_visible_holds',
2338 result_field => 'id'
2342 where => {id => $e->requestor->id}
2345 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2346 if($holds_object->{holds}) {
2347 $ctx->{holds} = $holds_object->{holds};
2349 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2351 return Apache2::Const::OK;
2354 sub load_myopac_payment_form {
2357 my $e = $self->editor;
2359 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2361 if ( ! $self->cgi->param('last_chance')) { # only do this once
2362 if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2363 if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')) {
2364 my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2365 my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2366 my $stripe = Business::Stripe->new(-api_key => $skey);
2367 my $intent = $stripe->api('post', 'payment_intents',
2368 amount => $self->ctx->{fines}->{balance_owed} * 100,
2369 currency => $currency || 'usd',
2370 description => 'User Database ID: ' . $self->ctx->{user}->id
2372 if ($stripe->success) {
2373 $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2375 $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2376 $self->ctx->{cc_configuration_error} = 1;
2379 } elsif ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'SmartPAY') {
2380 if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.enabled')) {
2381 my $location_id = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.location_id'));
2382 $self->ctx->{smartpay_locationid} = $location_id;
2383 my $customer_id = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.customer_id'));
2384 $self->ctx->{smartpay_customerid} = $customer_id;
2385 my $login = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.login'));
2386 my $password = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.password'));
2387 my $api_key = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.api_key'));
2388 my $server = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.server'));
2389 my $port = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.port'));
2390 my $base_target = "https://$server";
2391 $base_target .= ":$port" if $port;
2392 $base_target .= "/SMARTPAYAPI/WEBSMARTPAY.dll";
2395 my $target = $base_target . "?RequestSessionKey";
2396 $target .= "&CustomerID=$customer_id";
2397 $target .= "&LocationID=$location_id";
2398 $target .= "&UserName=$login";
2399 $target .= "&Password=$password";
2400 $target .= "&APIKey=$api_key";
2402 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2404 # generate a temporary cache token for our secret
2405 my $token = 'smartpay_' . md5_hex($$ . time() . rand());
2406 $target .= "&Secret=$token";
2408 my $ua = new LWP::UserAgent;
2410 # there has been API flux with whether to send API-Key and Secret as HTTP headers or URL params
2411 #my $req = GET($target, 'API-Key' => "$api_key", 'Secret' => "$token");
2412 my $req = GET($target);
2413 my $response = $ua->request($req);
2415 if ($response->is_success() && $response->content() !~ /HTML/) {
2416 $logger->info('SmartPAY initialized for ' . $self->editor->authtoken . ' with ' . $token);
2418 my $session_key = $response->content();
2420 # we'll test this secret key again in the create payment method and grab the payment_xacts in main_pay_init
2422 user => $self->ctx->{user}->id,
2423 session_key => $session_key,
2424 xacts => \@payment_xacts
2426 my $cache = OpenSRF::Utils::Cache->new('global');
2427 $cache->put_cache($token, $cache_args, 3600); # 1 hour
2429 # this will be for our follow-up call client-side
2431 $self->ctx->{smartpay_target} = $base_target . '?GetCreditForm';
2432 $self->ctx->{smartpay_target} .= '&SessionKey=' . $session_key;
2433 $self->ctx->{smartpay_target} .= "&CustomerID=$customer_id";
2434 $self->ctx->{smartpay_target} .= "&LocationID=$location_id";
2435 $self->ctx->{smartpay_target} .= '&PatronID=' . $self->ctx->{user}->id; # $e->requestor->id;
2436 my $psuedo_invoice_number = $self->cgi->param('xact') . ',' . $self->cgi->param('xact_misc');
2437 $psuedo_invoice_number =~ s/^,//;
2438 $self->ctx->{smartpay_target} .= "&InvNum=$psuedo_invoice_number";
2439 $self->ctx->{smartpay_target} .= '&Amount=' . sprintf("%.2f",$self->ctx->{fines}->{balance_owed});
2440 $self->ctx->{smartpay_target} .= '&URLPostBack=' . CGI::escapeHTML( $self->ctx->{hostname} );
2441 #$self->ctx->{smartpay_target} .= '&ScriptPostBack=' . CGI::escapeHTML('/cgi-bin/offline/echo1.pl');
2442 $self->ctx->{smartpay_target} .= '&URLReturn=' . CGI::escapeHTML( $self->ctx->{opac_root} . '/myopac/main_pay_init' );
2443 $self->ctx->{smartpay_target} .= '&URLCancel=' . CGI::escapeHTML( 'https://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/main');
2444 $self->ctx->{smartpay_target} .= '&UserName=&Password=&Field1=smartpay&Field2=&Field3=&ItemsData=';
2447 my $error = $response->content();
2448 $error =~ s/[\r\n]//g;
2449 $logger->error("Error initializing SmartPAY: $error");
2450 $self->ctx->{cc_configuration_error} = 1;
2456 if ($r) { return $r; }
2457 $r = $self->prepare_extended_user_info and return $r;
2459 return Apache2::Const::OK;
2462 # TODO: add other filter options as params/configs/etc.
2463 sub load_myopac_payments {
2465 my $limit = $self->cgi->param('limit') || 20;
2466 my $offset = $self->cgi->param('offset') || 0;
2467 my $e = $self->editor;
2469 $self->ctx->{payment_history_limit} = $limit;
2470 $self->ctx->{payment_history_offset} = $offset;
2473 $args->{limit} = $limit if $limit;
2474 $args->{offset} = $offset if $offset;
2476 if (my $max_age = $self->ctx->{get_org_setting}->(
2477 $e->requestor->home_ou, "opac.payment_history_age_limit"
2479 my $min_ts = DateTime->now(
2480 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2481 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2483 $logger->info("XXX min_ts: $min_ts");
2484 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2487 $self->ctx->{payments} = $U->simplereq(
2489 'open-ils.actor.user.payments.retrieve.atomic',
2490 $e->authtoken, $e->requestor->id, $args);
2492 return Apache2::Const::OK;
2495 # 1. caches the form parameters
2496 # 2. loads the credit card payment "Processing..." page
2497 sub load_myopac_pay_init {
2499 my $cache = OpenSRF::Utils::Cache->new('global');
2501 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2503 if (!@payment_xacts) {
2504 if ($self->cgi->param('Secret')) { # we stashed the xacts in the cache for SmartPAY
2505 my $smartpay_cache = $cache->get_cache($self->cgi->param('Secret'));
2506 @payment_xacts = @{$smartpay_cache->{xacts}};
2508 # for consistency with load_myopac_payment_form() and
2509 # to preserve backwards compatibility, if no xacts are
2510 # selected, assume all (applicable) transactions are wanted.
2511 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2512 return $stat if $stat;
2514 map { $_->{xact}->id } (
2515 @{$self->ctx->{fines}->{circulation}},
2516 @{$self->ctx->{fines}->{grocery}}
2521 return $self->generic_redirect unless @payment_xacts;
2523 my $cc_args = {"where_process" => 1};
2525 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2526 number cvv2 expire_year expire_month billing_first
2527 billing_last billing_address billing_city billing_state
2528 billing_zip stripe_payment_intent stripe_client_secret
2531 # mapping SmartPAY CGI parameters
2532 if ($self->cgi->param('Result')) {
2533 $cc_args->{smartpay_result} = $self->cgi->param('Result');
2535 if ($self->cgi->param('Secret')) {
2536 $cc_args->{smartpay_secret} = $self->cgi->param('Secret');
2538 if ($self->cgi->param('SessionKey')) {
2539 $cc_args->{smartpay_session} = $self->cgi->param('SessionKey');
2541 if ($self->cgi->param('CCNumber')) {
2542 $cc_args->{number} = $self->cgi->param('CCNumber');
2546 cc_args => $cc_args,
2547 user => $self->ctx->{user}->id,
2548 xacts => \@payment_xacts
2551 # generate a temporary cache token and cache the form data
2552 my $token = md5_hex($$ . time() . rand());
2553 $cache->put_cache($token, $cache_args, 30);
2555 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2557 # after we render the processing page, we quickly redirect to submit
2558 # the actual payment. The refresh url contains the payment token.
2559 # It also contains the list of xact IDs, which allows us to clear the
2560 # cache at the earliest possible time while leaving a trace of which
2561 # transactions we were processing, so the UI can bring the user back
2562 # to the payment form w/ the same xacts if the payment fails.
2564 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2565 $refresh .= ";xact=$_" for @payment_xacts;
2566 $self->ctx->{refresh} = $refresh;
2568 return Apache2::Const::OK;
2571 # retrieve the cached CC payment info and send off for processing
2572 sub load_myopac_pay {
2574 my $token = $self->ctx->{page_args}->[0];
2575 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2577 my $cache = OpenSRF::Utils::Cache->new('global');
2578 my $cache_args = $cache->get_cache($token);
2579 $cache->delete_cache($token);
2581 # this page is loaded immediately after the token is created.
2582 # if the cached data is not there, it's because of an invalid
2583 # token (or cache failure) and not because of a timeout.
2584 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2586 my @payment_xacts = @{$cache_args->{xacts}};
2587 my $cc_args = $cache_args->{cc_args};
2589 # as an added security check, verify the user submitting
2590 # the form is the same as the user whose data was cached
2591 return Apache2::Const::HTTP_BAD_REQUEST unless
2592 $cache_args->{user} == $self->ctx->{user}->id;
2594 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2597 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2599 # balance_owed is computed specifically from the fines we're paying
2600 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2601 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2602 return Apache2::Const::HTTP_BAD_REQUEST;
2606 "cc_args" => $cc_args,
2607 "userid" => $self->ctx->{user}->id,
2608 "payment_type" => "credit_card_payment",
2609 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2612 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2613 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2616 $self->ctx->{"payment_response"} = $resp;
2618 unless ($resp->{"textcode"}) {
2619 $self->ctx->{printable_receipt} = $U->simplereq(
2620 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2621 $self->editor->authtoken, $resp->{payments}
2625 return Apache2::Const::OK;
2628 sub load_myopac_receipt_print {
2631 $self->ctx->{printable_receipt} = $U->simplereq(
2632 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2633 $self->editor->authtoken, [$self->cgi->param("payment")]
2636 return Apache2::Const::OK;
2639 sub load_myopac_receipt_email {
2642 # The following ML method doesn't actually check whether the user in
2643 # question has an email address, so we do.
2644 if ($self->ctx->{user}->email) {
2645 $self->ctx->{email_receipt_result} = $U->simplereq(
2646 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2647 $self->editor->authtoken, [$self->cgi->param("payment")]
2650 $self->ctx->{email_receipt_result} =
2651 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2654 return Apache2::Const::OK;
2658 my ($self, $limit, $offset, $id_list) = @_;
2660 # XXX TODO: check for failure after various network calls
2662 # It may be unclear, but this result structure lumps circulation and
2663 # reservation fines together, and keeps grocery fines separate.
2664 $self->ctx->{"fines"} = {
2665 "circulation" => [],
2672 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2674 # TODO: This should really be a ML call, but the existing calls
2675 # return an excessive amount of data and don't offer streaming
2677 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2679 my $req = $cstore->request(
2680 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2682 usr => $self->editor->requestor->id,
2683 balance_owed => {'!=' => 0},
2684 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2689 mobts => [qw/grocery circulation reservation/],
2690 bresv => ['target_resource_type'],
2694 circ => ['target_copy'],
2695 acp => ['call_number'],
2698 order_by => { mobts => 'xact_start' },
2703 # Collect $$ amounts from each transaction for summing below.
2704 my (@paid_amounts, @owed_amounts, @balance_amounts);
2706 while(my $resp = $req->recv) {
2707 my $mobts = $resp->content;
2708 my $circ = $mobts->circulation;
2711 if($mobts->grocery) {
2712 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2713 $last_billing = pop(@billings);
2716 push(@paid_amounts, $mobts->total_paid);
2717 push(@owed_amounts, $mobts->total_owed);
2718 push(@balance_amounts, $mobts->balance_owed);
2720 my $marc_xml = undef;
2721 if ($mobts->xact_type eq 'reservation' and
2722 $mobts->reservation->target_resource_type->record) {
2723 $marc_xml = XML::LibXML->new->parse_string(
2724 $mobts->reservation->target_resource_type->record->marc
2726 } elsif ($mobts->xact_type eq 'circulation' and
2727 $circ->target_copy->call_number->id != -1) {
2728 $marc_xml = XML::LibXML->new->parse_string(
2729 $circ->target_copy->call_number->record->marc
2734 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2737 last_grocery_billing => $last_billing,
2738 marc_xml => $marc_xml
2745 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2746 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2747 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2752 sub prepare_fines_for_payment {
2753 # This assumes $self->prepare_fines has already been run
2757 if ($self->ctx->{fines}) {
2758 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2759 @{$self->ctx->{fines}->{circulation}},
2760 @{$self->ctx->{fines}->{grocery}}
2767 sub load_myopac_main {
2769 my $limit = $self->cgi->param('limit') || 0;
2770 my $offset = $self->cgi->param('offset') || 0;
2771 $self->ctx->{search_ou} = $self->_get_search_lib();
2772 $self->ctx->{user}->notes(
2773 $self->editor->search_actor_usr_message({
2774 usr => $self->ctx->{user}->id,
2778 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2781 sub load_myopac_update_email {
2783 my $e = $self->editor;
2784 my $ctx = $self->ctx;
2785 my $email = $self->cgi->param('email') || '';
2786 my $current_pw = $self->cgi->param('current_pw') || '';
2788 # needed for most up-to-date email address
2789 if (my $r = $self->prepare_extended_user_info) { return $r };
2791 return Apache2::Const::OK
2792 unless $self->cgi->request_method eq 'POST';
2794 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2795 $ctx->{invalid_email} = $email;
2796 return Apache2::Const::OK;
2799 my $stat = $U->simplereq(
2801 'open-ils.actor.user.email.update',
2802 $e->authtoken, $email, $current_pw);
2804 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2805 $ctx->{password_incorrect} = 1;
2806 return Apache2::Const::OK;
2809 unless ($self->cgi->param("redirect_to")) {
2810 my $url = $self->apache->unparsed_uri;
2811 $url =~ s/update_email/prefs/;
2813 return $self->generic_redirect($url);
2816 return $self->generic_redirect;
2819 sub load_myopac_update_username {
2821 my $e = $self->editor;
2822 my $ctx = $self->ctx;
2823 my $username = $self->cgi->param('username') || '';
2824 my $current_pw = $self->cgi->param('current_pw') || '';
2826 $self->prepare_extended_user_info;
2828 my $allow_change = 1;
2830 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2831 if(defined($lock_usernames) and $lock_usernames == 1) {
2832 # Policy says no username changes
2835 # We want this further down.
2836 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2837 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2838 if(!$username_unlimit) {
2840 # Default is "starts with a number"
2841 $regex_check = '^\d+';
2843 # You already have a username?
2844 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2849 if(!$allow_change) {
2850 my $url = $self->apache->unparsed_uri;
2851 $url =~ s/update_username/prefs/;
2853 return $self->generic_redirect($url);
2856 return Apache2::Const::OK
2857 unless $self->cgi->request_method eq 'POST';
2859 unless($username and $username !~ /\s/) { # any other username restrictions?
2860 $ctx->{invalid_username} = $username;
2861 return Apache2::Const::OK;
2864 # New username can't look like a barcode if we have a barcode regex
2865 if($regex_check and $username =~ /$regex_check/) {
2866 $ctx->{invalid_username} = $username;
2867 return Apache2::Const::OK;
2870 # New username has to look like a username if we have a username regex
2871 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2872 if($regex_check and $username !~ /$regex_check/) {
2873 $ctx->{invalid_username} = $username;
2874 return Apache2::Const::OK;
2877 if($username ne $e->requestor->usrname) {
2879 my $evt = $U->simplereq(
2881 'open-ils.actor.user.username.update',
2882 $e->authtoken, $username, $current_pw);
2884 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2885 $ctx->{password_incorrect} = 1;
2886 return Apache2::Const::OK;
2889 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2890 $ctx->{username_exists} = $username;
2891 return Apache2::Const::OK;
2895 my $url = $self->apache->unparsed_uri;
2896 $url =~ s/update_username/prefs/;
2898 return $self->generic_redirect($url);
2901 sub load_myopac_update_locale {
2903 my $e = $self->editor;
2904 my $ctx = $self->ctx;
2905 my $lang = $self->cgi->param('pref_lang') || '';
2906 my $current_pw = $self->cgi->param('current_pw') || '';
2908 $self->prepare_extended_user_info;
2910 my $locs = $U->simplereq(
2912 "open-ils.cstore.direct.config.i18n_locale.search.atomic",
2913 { "code" => { "!=" => undef } }
2917 foreach my $l (@$locs) { $user_locales{$l->code} = $l->name; }
2918 $self->ctx->{i18n_locales} = \%user_locales;
2920 return Apache2::Const::OK
2921 unless $self->cgi->request_method eq 'POST';
2923 if($lang ne $e->requestor->locale) {
2924 my $evt = $U->simplereq(
2926 'open-ils.actor.user.locale.update',
2927 $e->authtoken, $lang, $current_pw);
2929 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2930 $ctx->{password_incorrect} = 1;
2931 return Apache2::Const::OK;
2935 my $url = $self->apache->unparsed_uri;
2936 $url =~ s/update_locale/prefs/;
2938 return $self->generic_redirect($url);
2941 sub load_myopac_update_password {
2943 my $e = $self->editor;
2944 my $ctx = $self->ctx;
2946 return Apache2::Const::OK
2947 unless $self->cgi->request_method eq 'POST';
2949 my $current_pw = $self->cgi->param('current_pw') || '';
2950 my $new_pw = $self->cgi->param('new_pw') || '';
2951 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2953 unless($new_pw eq $new_pw2) {
2954 $ctx->{password_nomatch} = 1;
2955 return Apache2::Const::OK;
2958 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2961 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2962 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2965 if($pw_regex and $new_pw !~ /$pw_regex/) {
2966 $ctx->{password_invalid} = 1;
2967 return Apache2::Const::OK;
2970 my $evt = $U->simplereq(
2972 'open-ils.actor.user.password.update',
2973 $e->authtoken, $new_pw, $current_pw);
2976 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2977 $ctx->{password_incorrect} = 1;
2978 return Apache2::Const::OK;
2981 my $url = $self->apache->unparsed_uri;
2982 $url =~ s/update_password/prefs/;
2984 return $self->generic_redirect($url);
2987 sub _update_bookbag_metadata {
2988 my ($self, $bookbag) = @_;
2990 $bookbag->name($self->cgi->param("name"));
2991 $bookbag->description($self->cgi->param("description"));
2993 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2997 sub _get_lists_per_page {
3000 if($self->editor->requestor) {
3001 $self->timelog("Checking for opac.lists_per_page preference");
3002 # See if the user has a lists per page preference
3003 my $ipp = $self->editor->search_actor_user_setting({
3004 usr => $self->editor->requestor->id,
3005 name => 'opac.lists_per_page'
3007 $self->timelog("Got opac.lists_per_page preference");
3008 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
3010 return 10; # default
3013 sub _get_items_per_page {
3016 if($self->editor->requestor) {
3017 $self->timelog("Checking for opac.list_items_per_page preference");
3018 # See if the user has a list items per page preference
3019 my $ipp = $self->editor->search_actor_user_setting({
3020 usr => $self->editor->requestor->id,
3021 name => 'opac.list_items_per_page'
3023 $self->timelog("Got opac.list_items_per_page preference");
3024 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
3026 return 10; # default
3029 sub load_myopac_bookbags {
3031 my $e = $self->editor;
3032 my $ctx = $self->ctx;
3033 my $limit = $self->_get_lists_per_page || 10;
3034 my $offset = $self->cgi->param('offset') || 0;
3036 $ctx->{bookbags_limit} = $limit;
3037 $ctx->{bookbags_offset} = $offset;
3039 # for list item pagination
3040 my $item_limit = $self->_get_items_per_page;
3041 my $item_page = $self->cgi->param('item_page') || 1;
3042 my $item_offset = ($item_page - 1) * $item_limit;
3043 $ctx->{bookbags_item_page} = $item_page;
3045 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3046 $e->xact_begin; # replication...
3048 my $rv = $self->load_mylist;
3049 unless($rv eq Apache2::Const::OK) {
3054 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
3056 {owner => $e->requestor->id, btype => 'bookbag'}, {
3057 order_by => {cbreb => 'name'},
3065 if(!$ctx->{bookbags}) {
3067 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3070 # We load the user prefs to get their default bookbag.
3071 $self->_load_user_with_prefs;
3073 # We also want a total count of the user's bookbags.
3075 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
3077 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
3079 my $r = $e->json_query($q);
3080 $ctx->{bookbag_count} = $r->[0]->{'count'};
3082 # If the user wants a specific bookbag's items, load them.
3084 if ($self->cgi->param("bbid")) {
3086 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
3089 my $query = $self->_prepare_bookbag_container_query(
3090 $bookbag->id, $sorter, $modifier
3093 # Calculate total count of the items in selected bookbag.
3094 # This total includes record entries that have no assets available.
3095 my $bb_search_results = $U->simplereq(
3096 "open-ils.search", "open-ils.search.biblio.multiclass.query",
3097 {"limit" => 1, "offset" => 0}, $query
3098 ); # we only need the count, so do the actual search with limit=1
3100 if ($bb_search_results) {
3101 $ctx->{bb_item_count} = $bb_search_results->{count};
3103 $logger->warn("search failed in load_myopac_bookbags()");
3104 $ctx->{bb_item_count} = 0; # fallback value
3107 #calculate page count
3108 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
3110 if ( ($self->cgi->param("action") || '') eq "editmeta") {
3111 if (!$self->_update_bookbag_metadata($bookbag)) {
3113 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3116 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
3119 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
3120 if ($self->cgi->param($param)) {
3121 my @vals = $self->cgi->param($param);
3122 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3126 return $self->generic_redirect($url);
3130 # we're done with our CStoreEditor. Rollback here so
3131 # later calls don't cause a timeout, resulting in a
3132 # transaction rollback under the covers.
3136 # For list items pagination
3138 "limit" => $item_limit,
3139 "offset" => $item_offset
3142 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
3143 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3145 # capture pref_ou for callnumber filter/display
3146 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
3148 # search for local callnumbers for display
3149 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
3151 my (undef, @recs) = $self->get_records_and_facets(
3152 [ map {$_->target_biblio_record_entry->id} @$items ],
3155 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
3157 site => $ctx->{get_aou}->($focus_ou)->shortname,
3158 pref_lib => $ctx->{pref_ou}
3162 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
3164 $bookbag->items($items);
3168 # If we have add_rec, we got here from the "Add to new list"
3169 # or "See all" popmenu items.
3170 if (my $add_rec = $self->cgi->param('add_rec')) {
3171 $self->ctx->{add_rec} = $add_rec;
3172 # But not in the staff client, 'cause that breaks things.
3173 unless ($self->ctx->{is_staff}) {
3174 # allow caller to provide the where_from in cases where
3175 # the referer is an intermediate error page
3176 if ($self->cgi->param('where_from')) {
3177 $self->ctx->{where_from} = $self->cgi->param('where_from');
3179 $self->ctx->{where_from} = $self->ctx->{referer};
3180 if ( my $anchor = $self->cgi->param('anchor') ) {
3181 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3187 # this rollback may be a dupe, but that's OK because
3188 # cstoreditor ignores dupe rollbacks
3191 return Apache2::Const::OK;
3195 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3196 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3197 sub load_myopac_bookbag_update {
3198 my ($self, $action, $list_id, @hold_recs) = @_;
3199 my $e = $self->editor;
3200 my $cgi = $self->cgi;
3202 # save_notes is effectively another action, but is passed in a separate
3203 # CGI parameter for what are really just layout reasons.
3204 $action = 'save_notes' if $cgi->param('save_notes');
3205 $action ||= $cgi->param('action');
3207 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3209 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3210 my @selected_item = $cgi->param('selected_item');
3211 my $shared = $cgi->param('shared');
3212 my $move_cart = $cgi->param('move_cart');
3213 my $name = $cgi->param('name');
3214 my $description = $cgi->param('description');
3218 # bail out if user is attempting an action that requires
3219 # that at least one list item be selected
3220 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3221 ($action eq 'place_hold' || $action eq 'print' ||
3222 $action eq 'email' || $action eq 'del_item')) {
3223 my $url = $self->ctx->{referer};
3224 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3225 return $self->generic_redirect($url);
3228 # This url intentionally leaves off the edit_notes parameter, but
3229 # may need to add some back in for paging.
3231 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3232 $self->ctx->{opac_root} . "/myopac/lists?";
3234 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3235 if ($cgi->param($param)) {
3236 my @vals = $cgi->param($param);
3237 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3241 if ($action eq 'create') {
3244 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3246 $list->description($description);
3247 $list->owner($e->requestor->id);
3248 $list->btype('bookbag');
3249 $list->pub($shared ? 't' : 'f');
3250 $success = $U->simplereq('open-ils.actor',
3251 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3252 if (ref($success) ne 'HASH') {
3253 $list_id = (ref($success)) ? $success->id : $success;
3254 if (scalar @add_rec) {
3255 foreach my $add_rec (@add_rec) {
3256 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3257 $item->bucket($list_id);
3258 $item->target_biblio_record_entry($add_rec);
3259 $success = $U->simplereq('open-ils.actor',
3260 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3261 last unless $success;
3265 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3266 foreach my $add_rec (@$list) {
3267 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3268 $item->bucket($list_id);
3269 $item->target_biblio_record_entry($add_rec);
3270 $success = $U->simplereq('open-ils.actor',
3271 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3272 last unless $success;
3274 $self->clear_anon_cache;
3277 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3280 $self->ctx->{bucket_failure_noname} = 1;
3283 } elsif($action eq 'place_hold') {
3285 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3286 my $from_basket = scalar(@hold_recs);
3287 unless (@hold_recs) {
3288 if (@selected_item) {
3289 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3290 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3294 return Apache2::Const::OK unless @hold_recs;
3295 $logger->info("placing holds from list page on: @hold_recs");
3297 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3298 $url .= ';hold_target=' . $_ for @hold_recs;
3299 $url .= ';from_basket=1' if $from_basket;
3300 foreach my $param (('loc', 'qtype', 'query')) {
3301 if ($cgi->param($param)) {
3302 my @vals = $cgi->param($param);
3303 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3306 return $self->generic_redirect($url);
3308 } elsif ($action eq 'print') {
3309 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3310 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3311 if (!$incoming_sort) {
3312 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3314 if (!$incoming_sort) {
3315 $incoming_sort = 'author';
3318 $incoming_sort =~ s/sort.*$//;
3320 $self->ctx->{sort} = $incoming_sort;
3321 $self->ctx->{sort_dir} = $sort_dir;
3323 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3324 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3325 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3326 return $self->load_mylist_print($temp_cache_key);
3327 } elsif ($action eq 'email') {
3328 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3329 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3330 if (!$incoming_sort) {
3331 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3333 if (!$incoming_sort) {
3334 $incoming_sort = 'author';
3337 $incoming_sort =~ s/sort.*$//;
3339 $self->ctx->{sort} = $incoming_sort;
3340 $self->ctx->{sort_dir} = $sort_dir;
3342 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3343 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3344 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3345 return $self->load_mylist_email($temp_cache_key);
3348 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3350 return Apache2::Const::HTTP_BAD_REQUEST unless
3351 $list and $list->owner == $e->requestor->id;
3354 if($action eq 'delete') {
3355 $success = $U->simplereq('open-ils.actor',
3356 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3358 # We check to see if we're deleting the user's default list.
3359 $self->_load_user_with_prefs;
3360 my $settings_map = $self->ctx->{user_setting_map};
3361 if ($$settings_map{'opac.default_list'} == $list_id) {
3362 # We unset the user's opac.default_list setting.
3363 $success = $U->simplereq(
3365 'open-ils.actor.patron.settings.update',
3368 { 'opac.default_list' => 0 }
3372 } elsif($action eq 'show') {
3373 unless($U->is_true($list->pub)) {
3375 $success = $U->simplereq('open-ils.actor',
3376 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3379 } elsif($action eq 'hide') {
3380 if($U->is_true($list->pub)) {
3382 $success = $U->simplereq('open-ils.actor',
3383 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3386 } elsif($action eq 'rename') {
3389 $success = $U->simplereq('open-ils.actor',
3390 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3393 } elsif($action eq 'add_rec') {
3394 foreach my $add_rec (@add_rec) {
3395 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3396 $item->bucket($list_id);
3397 $item->target_biblio_record_entry($add_rec);
3398 $success = $U->simplereq('open-ils.actor',
3399 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3400 last unless $success;
3402 # Redirect back where we came from if we have an anchor parameter:
3403 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3404 $url = $self->ctx->{referer};
3405 $url =~ s/#.*|$/#$anchor/;
3406 } elsif ($cgi->param('where_from')) {
3407 # Or, if we have a "where_from" parameter.
3408 $url = $cgi->param('where_from');
3410 } elsif ($action eq 'del_item') {
3411 foreach (@selected_item) {
3412 $success = $U->simplereq(
3414 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3416 last unless $success;
3418 } elsif ($action eq 'save_notes') {
3419 $success = $self->update_bookbag_item_notes;
3420 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3421 } elsif ($action eq 'make_default') {
3422 $success = $U->simplereq(
3424 'open-ils.actor.patron.settings.update',
3427 { 'opac.default_list' => $list_id }
3429 } elsif ($action eq 'remove_default') {
3430 $success = $U->simplereq(
3432 'open-ils.actor.patron.settings.update',
3435 { 'opac.default_list' => 0 }
3439 return $self->generic_redirect($url) if $success;
3441 $self->ctx->{where_from} = $cgi->param('where_from');
3442 $self->ctx->{bucket_action} = $action;
3443 $self->ctx->{bucket_action_failed} = 1;
3444 return Apache2::Const::OK;
3447 sub update_bookbag_item_notes {
3449 my $e = $self->editor;
3451 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3452 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3454 # We're going to leverage an API call that's already been written to check
3455 # permissions appropriately.
3457 my $a = create OpenSRF::AppSession("open-ils.actor");
3458 my $method = "open-ils.actor.container.item_note.cud";
3460 for my $note_key (@note_keys) {
3463 my $id = ($note_key =~ /(\d+)/)[0];
3466 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3467 my $event = $e->die_event;
3468 $self->apache->log->warn(
3469 "error retrieving cbrebin id $id, got event " .
3473 $self->ctx->{bucket_action_event} = $event;
3477 if (length($self->cgi->param($note_key))) {
3478 $note->ischanged(1);
3479 $note->note($self->cgi->param($note_key));
3481 $note->isdeleted(1);
3484 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3486 if (defined $U->event_code($r)) {
3487 $self->apache->log->warn(
3488 "attempt to modify cbrebin " . $note->id .
3489 " returned event " . $r->{textcode}
3493 $self->ctx->{bucket_action_event} = $r;
3498 for my $item_key (@item_keys) {
3499 my $id = int(($item_key =~ /(\d+)/)[0]);
3500 my $text = $self->cgi->param($item_key);
3503 next unless length $text;
3505 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3510 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3512 if (defined $U->event_code($r)) {
3513 $self->apache->log->warn(
3514 "attempt to create cbrebin for item " . $note->item .
3515 " returned event " . $r->{textcode}
3519 $self->ctx->{bucket_action_event} = $r;
3528 sub load_myopac_bookbag_print {
3531 my $id = int($self->cgi->param("list"));
3533 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3536 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3540 # Get the bookbag object itself, assuming we're allowed to.
3541 if ($self->editor->allowed("VIEW_CONTAINER")) {
3543 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3545 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3549 "owner" => $self->editor->requestor->id,
3553 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3555 $bbag = pop @$bookbags;
3558 # If we have a bookbag we're allowed to look at, issue the A/T event
3559 # to get CSV, passing as a user param that search query we built before.
3561 $self->ctx->{csv} = $U->fire_object_event(
3562 undef, "container.biblio_record_entry_bucket.csv",
3563 $bbag, $self->editor->requestor->home_ou,
3564 undef, {"item_search" => $item_search}
3568 # Create a reasonable filename and set the content disposition to
3569 # provoke browser download dialogs.
3570 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3572 return $self->set_file_download_headers("$filename.csv");
3575 sub load_myopac_circ_history_export {
3577 my $e = $self->editor;
3578 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3580 my $circs = $self->fetch_user_circ_history(1);
3582 $self->ctx->{csv}->{circs} = $circs;
3583 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3587 sub load_myopac_reservations {
3589 my $e = $self->editor;
3590 my $ctx = $self->ctx;
3592 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3593 $e->authtoken, undef
3596 $ctx->{reservations} = $upcoming;
3597 return Apache2::Const::OK;
3601 sub load_password_reset {
3603 my $cgi = $self->cgi;
3604 my $ctx = $self->ctx;
3605 my $barcode = $cgi->param('barcode');
3606 my $username = $cgi->param('username');
3607 my $email = $cgi->param('email');
3608 my $pwd1 = $cgi->param('pwd1');
3609 my $pwd2 = $cgi->param('pwd2');
3610 my $uuid = $ctx->{page_args}->[0];
3614 $logger->info("patron password reset with uuid $uuid");
3616 if ($pwd1 and $pwd2) {
3618 if ($pwd1 eq $pwd2) {
3620 my $response = $U->simplereq(
3622 'open-ils.actor.patron.password_reset.commit',
3625 $logger->info("patron password reset response " . Dumper($response));
3627 if ($U->event_code($response)) { # non-success event
3629 my $code = $response->{textcode};
3631 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3632 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3635 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3636 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3641 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3644 } else { # passwords not equal
3646 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3649 } else { # 2 password values needed
3651 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3654 } elsif ($barcode or $username) {
3656 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3657 push(@params, $email) if $email;
3661 'open-ils.actor.patron.password_reset.request', @params);
3663 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3666 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3667 return Apache2::Const::OK;