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);
15 $Data::Dumper::Indent = 0;
17 use DateTime::Format::ISO8601;
18 my $U = 'OpenILS::Application::AppUtils';
19 use List::MoreUtils qw/uniq/;
21 sub prepare_extended_user_info {
24 my $e = $self->editor;
26 # are we already in a transaction?
27 my $local_xact = !$e->{xact_id};
28 $e->xact_begin if $local_xact;
30 # keep the original user object so we can restore
31 # login-specific data (e.g. workstation)
32 my $usr = $self->ctx->{user};
34 $self->ctx->{user} = $self->editor->retrieve_actor_user([
35 $self->ctx->{user}->id,
39 au => [qw/card home_ou addresses ident_type billing_address waiver_entries/, @extra_flesh],
40 "aou" => ["billing_address"]
45 $e->rollback if $local_xact;
47 $self->ctx->{user}->wsid($usr->wsid);
48 $self->ctx->{user}->ws_ou($usr->ws_ou);
50 # discard replaced (negative-id) addresses.
51 $self->ctx->{user}->addresses([
52 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
54 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
55 unless $self->ctx->{user};
60 # Given an event returned by a failed attempt to create a hold, do we have
61 # permission to override? XXX Should the permission check be scoped to a
62 # given org_unit context?
63 sub test_could_override {
64 my ($self, $event) = @_;
66 return 0 unless $event;
67 return 1 if $self->editor->allowed($event->{textcode} . ".override");
68 return 1 if $event->{"fail_part"} and
69 $self->editor->allowed($event->{"fail_part"} . ".override");
73 # Find out whether we care that local copies are available
74 sub local_avail_concern {
75 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
77 my $would_block = $self->ctx->{get_org_setting}->
78 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
80 $self->ctx->{get_org_setting}->
81 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
82 not $self->cgi->param("override")
83 ) unless $would_block;
85 if ($would_block or $would_alert) {
87 "hold_target" => $hold_target,
88 "hold_type" => $hold_type,
89 "org_unit" => $pickup_lib
91 my $local_avail = $U->simplereq(
93 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
96 "copy availability information for " . Dumper($args) .
97 " is " . Dumper($local_avail)
99 if (%$local_avail) { # if hash not empty
100 $self->ctx->{hold_copy_available} = $local_avail;
101 return ($would_block, $would_alert);
109 # user : au object, fleshed
110 sub load_myopac_prefs {
112 my $cgi = $self->cgi;
113 my $e = $self->editor;
114 my $pending_addr = $cgi->param('pending_addr');
115 my $replace_addr = $cgi->param('replace_addr');
116 my $delete_pending = $cgi->param('delete_pending');
118 $self->prepare_extended_user_info;
119 my $user = $self->ctx->{user};
121 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
122 if(defined($lock_usernames) and $lock_usernames == 1) {
123 # Policy says no username changes
124 $self->ctx->{username_change_disallowed} = 1;
126 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
127 if(!$username_unlimit) {
128 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
130 # Default is "starts with a number"
131 $regex_check = '^\d+';
133 # You already have a username?
134 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
135 $self->ctx->{username_change_disallowed} = 1;
140 return Apache2::Const::OK unless
141 $pending_addr or $replace_addr or $delete_pending;
143 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
146 if( $pending_addr ) { # update an existing pending address
148 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
149 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
150 $paddr->$_( $cgi->param($_) ) for @form_fields;
152 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
154 $paddr = Fieldmapper::actor::user_address->new;
156 $paddr->usr($user->id);
157 $paddr->pending('t');
158 $paddr->replaces($replace_addr);
159 $paddr->$_( $cgi->param($_) ) for @form_fields;
161 } elsif( $delete_pending ) {
162 $paddr = $e->retrieve_actor_user_address($delete_pending);
163 return Apache2::Const::HTTP_BAD_REQUEST unless
164 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
165 $paddr->isdeleted(1);
168 my $resp = $U->simplereq(
170 'open-ils.actor.user.address.pending.cud',
171 $e->authtoken, $paddr);
173 if( $U->event_code($resp) ) {
174 $logger->error("Error updating pending address: $resp");
175 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
178 # in light of these changes, re-fetch latest data
180 $self->prepare_extended_user_info;
183 return Apache2::Const::OK;
186 sub load_myopac_prefs_notify {
188 my $e = $self->editor;
191 my $stat = $self->_load_user_with_prefs;
192 return $stat if $stat;
194 my $user_prefs = $self->fetch_optin_prefs;
195 $user_prefs = $self->update_optin_prefs($user_prefs)
196 if $self->cgi->request_method eq 'POST';
198 $self->ctx->{opt_in_settings} = $user_prefs;
200 return Apache2::Const::OK
201 unless $self->cgi->request_method eq 'POST';
204 my $set_map = $self->ctx->{user_setting_map};
208 opac.default_sms_notify
210 my $val = $self->cgi->param($key);
211 $settings{$key}= $val unless $$set_map{$key} eq $val;
214 my $key = 'opac.default_sms_carrier';
215 my $val = $self->cgi->param('sms_carrier');
216 $settings{$key}= $val unless $$set_map{$key} eq $val;
218 $key = 'opac.hold_notify';
219 my @notify_methods = ();
220 if ($self->cgi->param($key . ".email") eq 'on') {
221 push @notify_methods, "email";
223 if ($self->cgi->param($key . ".phone") eq 'on') {
224 push @notify_methods, "phone";
226 if ($self->cgi->param($key . ".sms") eq 'on') {
227 push @notify_methods, "sms";
229 $val = join("|",@notify_methods);
230 $settings{$key}= $val unless $$set_map{$key} eq $val;
232 # Send the modified settings off to be saved
235 'open-ils.actor.patron.settings.update',
236 $self->editor->authtoken, undef, \%settings);
238 # re-fetch user prefs
239 $self->ctx->{updated_user_settings} = \%settings;
241 # update holds: check if any changes affect any holds
242 my @llchgs = $self->_parse_prefs_notify_hold_related();
245 if ( $self->cgi->param('hasHoldsChanges') ) {
246 # propagate pref_notify changes to holds
247 for my $chset (@llchgs){
248 # FIXME is this still needed?
253 my $holds = $U->simplereq('open-ils.circ', 'open-ils.circ.holds.retrieve.by_usr.with_notify',
254 $e->authtoken, $e->requestor->id);
258 my $default_phone_changes = {};
259 my $sms_changes = {};
263 for my $chset (@llchgs) {
264 next if scalar(@$chset) < 3;
265 my ($old, $new, $field) = @$chset;
267 my $bool = $field =~ /_notify/ ? 1 : 0;
269 # find holds that would change
271 foreach my $hold (@$holds) {
272 if ($field eq 'email_notify') {
273 my $curr = $hold->{$field} eq 't' ? 'true' : 'false';
274 push @$affected, $hold if $curr ne $new;
275 } elsif ($field eq 'default_phone') {
276 my $old_phone = $hold->{phone_notify} // '';
277 $new_phone = $new // '';
278 push @{ $default_phone_changes->{ $old_phone } }, $hold->{id}
279 if $old_phone ne $new_phone;
280 } elsif ($field eq 'phone_notify') {
281 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
282 push @$affected, $hold if $curr ne $new;
283 } elsif ($field eq 'sms_notify') {
284 my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
285 push @$affected, $hold if $curr ne $new;
286 } elsif ($field eq 'sms_info') {
287 my $old_carrier = $hold->{'sms_carrier'} // '';
288 my $old_sms = $hold->{'sms_notify'} // '';
289 $new_carrier = $new->{carrier} // '';
290 $new_sms = $new->{sms} // '';
291 if (!($old_carrier eq $new_carrier && $old_sms eq $new_sms)) {
292 push @{ $sms_changes->{ join("\t", $old_carrier, $old_sms) } }, $hold->{id};
297 # append affected array to chset
298 if (scalar(@$affected) > 0){
299 push(@$chset, [ map { $_->{id} } @$affected ]);
300 push(@ffectedChgs, $chset);
305 foreach my $old_phone (keys %$default_phone_changes) {
306 push(@ffectedChgs, [ $old_phone, $new_phone, 'default_phone', $default_phone_changes->{$old_phone} ]);
308 foreach my $old_sms_info (keys %$sms_changes) {
309 my ($old_carrier, $old_sms) = split /\t/, $old_sms_info;
311 { carrier => $old_carrier, sms => $old_sms },
312 { carrier => $new_carrier, sms => $new_sms },
314 $sms_changes->{$old_sms_info}
318 if ( scalar(@ffectedChgs) ){
319 $self->ctx->{affectedChgs} = \@ffectedChgs;
324 return $self->_load_user_with_prefs || Apache2::Const::OK;
327 sub _parse_prefs_notify_hold_related {
330 my $for_update = shift;
332 # create an array of change arrays
335 my @phone_notify = $self->cgi->multi_param('phone_notify[]');
336 push(@chgs, \@phone_notify) if scalar(@phone_notify);
338 my $turning_on_phone_notify = !$for_update &&
339 scalar(@phone_notify) &&
340 $phone_notify[1] eq 'true';
341 my $turning_off_phone_notify = !$for_update &&
342 scalar(@phone_notify) &&
343 $phone_notify[1] eq 'false';
345 my $changing_default_phone = 0;
346 if (!$turning_off_phone_notify) {
347 my @default_phone = $self->cgi->multi_param('default_phone[]');
349 while (scalar(@default_phone) > 0) {
350 my $chg = [ splice(@default_phone, 0, 4) ];
351 if (scalar(@default_phone) > 0 && $default_phone[0] eq 'on') {
352 push @$chg, shift(@default_phone);
354 $changing_default_phone = 1;
358 if (scalar(@default_phone)) {
359 push @chgs, \@default_phone;
360 $changing_default_phone = 1;
365 if ($turning_on_phone_notify && $changing_default_phone) {
366 # we don't need to have both the phone_notify and default_phone
367 # changes; the latter will suffice
368 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
369 } elsif ($turning_on_phone_notify && !$changing_default_phone) {
370 # replace the phone_notify change with a default_phone change
371 @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
372 my $default_phone = $self->cgi->param('opac.default_phone'); # we assume this is set
373 push @chgs, [ '', $default_phone, 'default_phone' ];
377 # ... since both carrier and number are needed to send an SMS notifcation,
378 # we need to treat the pair as a unit
379 my @sms_notify = $self->cgi->multi_param('sms_notify[]');
380 push(@chgs, \@sms_notify) if scalar(@sms_notify);
382 my $turning_on_sms_notify = !$for_update &&
383 scalar(@sms_notify) &&
384 $sms_notify[1] eq 'true';
385 my $turning_off_sms_notify = !$for_update &&
386 scalar(@sms_notify) &&
387 $sms_notify[1] eq 'false';
389 my $changing_sms_info = 0;
390 if (!$turning_off_sms_notify) {
391 my @sms_carrier = $self->cgi->multi_param('default_sms_carrier_id[]');
392 my @sms = $self->cgi->multi_param('default_sms[]');
394 if (scalar(@sms) || scalar(@sms_carrier)) {
395 my $new_carrier = scalar(@sms_carrier) ? $sms_carrier[1] : $self->cgi->param('sms_carrier');
396 my $new_sms = scalar(@sms) ? $sms[1] : $self->cgi->param('opac.default_sms_notify');
398 { carrier => '', sms => '' },
399 { carrier => $new_carrier, sms => $new_sms },
402 $changing_sms_info = 1;
406 my @sms_info = $self->cgi->multi_param('sms_info[]'); # only sent by confirmation page
407 if (scalar(@sms_info)) {
408 while (scalar(@sms_info) > 0) {
409 my $chg = [ splice(@sms_info, 0, 4) ];
410 if (scalar(@sms_info) > 0 && $sms_info[0] eq 'on') {
411 push @$chg, shift(@sms_info);
412 my ($carrier, $sms) = split /,/, $chg->[0], -1;
413 $chg->[0] = { carrier => $carrier, sms => $sms };
414 ($carrier, $sms) = split /,/, $chg->[1], -1;
415 $chg->[1] = { carrier => $carrier, sms => $sms };
417 $changing_sms_info = 1;
422 if ($turning_on_sms_notify && $changing_sms_info) {
423 # we don't need to have both the sms_notify and sms_info
424 # changes; the latter will suffice
425 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
426 } elsif ($turning_on_sms_notify && !$changing_sms_info) {
427 # replace the sms_notify change with a sms_info change
428 @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
430 carrier => $self->cgi->param('sms_carrier'),
431 sms => $self->cgi->param('opac.default_sms_notify'),
433 push @chgs, [ { carrier => '', sms => ''}, $sms_info, 'sms_info' ];
436 my @email_notify = $self->cgi->multi_param('email_notify[]');
437 push(@chgs, \@email_notify) if scalar(@email_notify);
440 # if we're updating, keep only the ones that have been
441 # explicitly checked by the user
442 @chgs = grep { scalar(@$_) == 5 && $_->[4] eq 'on' } @chgs;
447 sub load_myopac_prefs_notify_changed_holds {
449 my $e = $self->editor;
451 my $hasChanges = $self->cgi->param('hasHoldsChanges');
453 return $self->_load_user_with_prefs || Apache2::Const::OK unless $hasChanges;
455 my @ll = $self->_parse_prefs_notify_hold_related(1);
459 my ($old, $new, $type, $holdids, $doit) = @$chset;
460 next if $doit ne 'on';
462 # parse string list into array list
463 my @holdids = split(',', $holdids);
465 if ($type =~ /_notify/){
466 # translate true/false string into 1/0
467 $old = $old eq 'true' ? 1 : 0;
468 $new = $new eq 'true' ? 1 : 0;
472 if ($type eq 'sms_info') {
473 if ($new->{carrier} eq '' && $new->{sms} eq '') {
474 # clear SMS number first to avoid check contrainst issue
475 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
476 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
477 push (@updates, $update) if (scalar(@$update) > 0);
478 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
479 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
480 push (@updates, $update) if (scalar(@$update) > 0);
482 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
483 $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
484 push (@updates, $update) if (scalar(@$update) > 0);
485 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
486 $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
487 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, $new, $type);
493 # append affected array to chset
494 if (scalar(@$update) > 0){
495 push(@updates, $update);
500 $self->ctx->{'updated'} = \@updates;
502 return $self->_load_user_with_prefs || Apache2::Const::OK;
506 sub fetch_optin_prefs {
508 my $e = $self->editor;
510 # fetch all of the opt-in settings the user has access to
511 # XXX: user's should in theory have options to opt-in to notices
512 # for remote locations, but that opens the door for a large
513 # set of generally un-used opt-ins.. needs discussion
514 my $opt_ins = $U->simplereq(
516 'open-ils.actor.event_def.opt_in.settings.atomic',
517 $e->authtoken, $e->requestor->home_ou);
519 # some opt-ins are staff-only
520 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
522 # fetch user setting values for each of the opt-in settings
523 my $user_set = $U->simplereq(
525 'open-ils.actor.patron.settings.retrieve',
528 [map {$_->name} @$opt_ins]
531 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
534 sub load_myopac_messages {
536 my $e = $self->editor;
537 my $ctx = $self->ctx;
538 my $cgi = $self->cgi;
540 my $limit = $cgi->param('limit') || 20;
541 my $offset = $cgi->param('offset') || 0;
543 my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
546 my $action = $cgi->param('action') || '';
548 my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
549 if ($changed > 0 || $failed > 0) {
550 $ctx->{message_update_action} = $action;
551 $ctx->{message_update_changed} = $changed;
552 $ctx->{message_update_failed} = $failed;
553 $self->update_dashboard_stats();
557 my $single = $cgi->param('single') || 0;
558 my $id = $cgi->param('message_id');
562 if (!$action && $single && $id) {
563 $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
564 if (scalar(@$messages) == 1) {
565 $ctx->{display_single_message} = 1;
566 $ctx->{patron_message_id} = $id;
572 # fetch all the messages
573 ($ctx->{patron_messages_count}, $messages) =
574 $self->_fetch_user_messages($pcrud, $offset, $limit);
579 foreach my $aum (@$messages) {
581 push @{ $ctx->{patron_messages} }, {
583 title => $aum->title,
584 message => $aum->message,
585 create_date => $aum->create_date,
586 is_read => defined($aum->read_date) ? 1 : 0,
587 library => $aum->sending_lib->name,
591 $ctx->{patron_messages_limit} = $limit;
592 $ctx->{patron_messages_offset} = $offset;
594 return Apache2::Const::OK;
597 sub _fetch_and_mark_read_single_message {
602 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
603 my $messages = $pcrud->request(
604 'open-ils.pcrud.search.auml.atomic',
605 $self->editor->authtoken,
607 usr => $self->editor->requestor->id,
613 flesh_fields => { auml => ['sending_lib'] },
617 $messages->[0]->read_date('now');
619 'open-ils.pcrud.update.auml',
620 $self->editor->authtoken,
624 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
626 $self->update_dashboard_stats();
631 sub _fetch_user_messages {
637 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
639 my $all_messages = $pcrud->request(
640 'open-ils.pcrud.id_list.auml.atomic',
641 $self->editor->authtoken,
643 usr => $self->editor->requestor->id,
649 my $messages = $pcrud->request(
650 'open-ils.pcrud.search.auml.atomic',
651 $self->editor->authtoken,
653 usr => $self->editor->requestor->id,
658 flesh_fields => { auml => ['sending_lib'] },
659 order_by => { auml => 'create_date DESC' },
664 return scalar(@$all_messages), $messages;
667 sub _handle_message_action {
671 my $cgi = $self->cgi;
673 my @ids = $cgi->param('message_id');
674 return (0, 0) unless @ids;
678 $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
680 my $aum = $pcrud->request(
681 'open-ils.pcrud.retrieve.auml',
682 $self->editor->authtoken,
686 if ($action eq 'mark_read') {
687 $aum->read_date('now');
688 } elsif ($action eq 'mark_unread') {
689 $aum->clear_read_date();
690 } elsif ($action eq 'mark_deleted') {
693 $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
698 $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
700 $failed = scalar(@ids);
702 $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
704 return ($changed, $failed);
707 sub _load_lists_and_settings {
709 my $e = $self->editor;
710 my $stat = $self->_load_user_with_prefs;
713 my $setting_map = $self->ctx->{user_setting_map};
714 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
715 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
717 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
718 order_by => {cbreb => 'name'},
719 limit => $self->cgi->param('limit') || 10,
720 offset => $self->cgi->param('offset') || 0
724 # We also want a total count of the user's bookbags.
726 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
728 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
730 my $r = $e->json_query($q);
731 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
732 # Someone has requested that we use the default list's name
733 # rather than "Default List."
736 'select' => {'cbreb' => ['name']},
738 'where' => {'id' => $exclude}
740 $r = $e->json_query($q);
741 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
749 sub update_optin_prefs {
751 my $user_prefs = shift;
752 my $e = $self->editor;
753 my @settings = $self->cgi->param('setting');
756 # apply now-true settings
757 for my $applied (@settings) {
758 # see if setting is already applied to this user
759 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
760 $newsets{$applied} = OpenSRF::Utils::JSON->true;
763 # remove now-false settings
764 for my $pref (grep { $_->{value} } @$user_prefs) {
765 $newsets{$pref->{cust}->name} = undef
766 unless grep { $_ eq $pref->{cust}->name } @settings;
771 'open-ils.actor.patron.settings.update',
772 $e->authtoken, $e->requestor->id, \%newsets);
774 # update the local prefs to match reality
775 for my $pref (@$user_prefs) {
776 $pref->{value} = $newsets{$pref->{cust}->name}
777 if exists $newsets{$pref->{cust}->name};
783 sub _load_user_with_prefs {
785 my $stat = $self->prepare_extended_user_info('settings');
786 return $stat if $stat; # not-OK
788 $self->ctx->{user_setting_map} = {
789 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
790 @{$self->ctx->{user}->settings}
796 sub _get_bookbag_sort_params {
797 my ($self, $param_name) = @_;
799 # The interface that feeds this cgi parameter will provide a single
800 # argument for a QP sort filter, and potentially a modifier after a period.
801 # In practice this means the "sort" parameter will be something like
802 # "titlesort" or "authorsort.descending".
803 my $sorter = $self->cgi->param($param_name) || "";
806 $sorter =~ s/^(.*?)\.(.*)/$1/;
807 $modifier = $2 || undef;
810 return ($sorter, $modifier);
813 sub _prepare_bookbag_container_query {
814 my ($self, $container_id, $sorter, $modifier) = @_;
817 "container(bre,bookbag,%d,%s)%s%s",
818 $container_id, $self->editor->authtoken,
819 ($sorter ? " sort($sorter)" : ""),
820 ($modifier ? "#$modifier" : "")
824 sub _prepare_anonlist_sorting_query {
825 my ($self, $list, $sorter, $modifier) = @_;
828 "record_list(%s)%s%s",
830 ($sorter ? " sort($sorter)" : ""),
831 ($modifier ? "#$modifier" : "")
836 sub load_myopac_prefs_settings {
841 opac.default_search_location
842 opac.default_pickup_location
843 opac.temporary_list_no_warn
846 my $stat = $self->_load_user_with_prefs;
847 return $stat if $stat;
849 # if behind-desk holds are supported and the user
850 # setting which controls the value is opac-visible,
851 # add the setting to the list of settings to manage.
852 # note: this logic may need to be changed later to
853 # check whether behind-the-desk holds are supported
854 # anywhere the patron may select as a pickup lib.
855 my $e = $self->editor;
856 my $bdous = $self->ctx->{get_org_setting}->(
857 $e->requestor->home_ou,
858 'circ.holds.behind_desk_pickup_supported');
862 $e->retrieve_config_usr_setting_type(
863 'circ.holds_behind_desk');
865 if ($U->is_true($setting->opac_visible)) {
866 push(@user_prefs, 'circ.holds_behind_desk');
867 $self->ctx->{behind_desk_supported} = 1;
871 my $use_privacy_waiver = $self->ctx->{get_org_setting}->(
872 $e->requestor->home_ou, 'circ.privacy_waiver');
874 return Apache2::Const::OK
875 unless $self->cgi->request_method eq 'POST';
877 # some setting values from the form don't match the
878 # required value/format for the db, so they have to be
879 # individually translated.
882 my $set_map = $self->ctx->{user_setting_map};
884 foreach my $key (@user_prefs) {
885 my $val = $self->cgi->param($key);
886 $settings{$key}= $val unless $$set_map{$key} eq $val;
889 # Used by the settings update form when warning on history delete.
890 my $clear_circ_history = 0;
891 my $clear_hold_history = 0;
893 # true if we need to show the warning on next page load.
894 my $hist_warning_needed = 0;
895 my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
897 my $now = DateTime->now->strftime('%F');
899 qw/history.circ.retention_start history.hold.retention_start/) {
901 my $val = $self->cgi->param($key);
902 if($val and $val eq 'on') {
903 # Set the start time to 'now' unless a start time already exists for the user
904 $settings{$key} = $now unless $$set_map{$key};
908 next unless $$set_map{$key}; # nothing to do
910 $clear_circ_history = 1 if $key =~ /circ/;
911 $clear_hold_history = 1 if $key =~ /hold/;
913 if (!$hist_clear_confirmed) {
914 # when clearing circ history, only warn if history data exists.
916 if ($clear_circ_history) {
918 if ($self->fetch_user_circ_history(0, 1)->[0]) {
919 $hist_warning_needed = 1;
920 next; # no history updates while confirmation pending
925 my $one_hold = $e->json_query({
929 transform => 'action.usr_visible_holds',
934 where => {id => $e->requestor->id},
939 $hist_warning_needed = 1;
940 next; # no history updates while confirmation pending
945 $settings{$key} = undef;
947 if ($key eq 'history.circ.retention_start') {
948 # delete existing circulation history data.
951 'open-ils.actor.history.circ.clear',
952 $self->editor->authtoken);
957 # Warn patrons before clearing circ/hold history
958 if ($hist_warning_needed) {
959 $self->ctx->{clear_circ_history} = $clear_circ_history;
960 $self->ctx->{clear_hold_history} = $clear_hold_history;
961 $self->ctx->{confirm_history_delete} = 1;
964 # Send the modified settings off to be saved
967 'open-ils.actor.patron.settings.update',
968 $self->editor->authtoken, undef, \%settings);
970 $self->ctx->{updated_user_settings} = \%settings;
972 if ($use_privacy_waiver) {
974 my $saved_entries = ();
975 my @waiver_types = qw/place_holds pickup_holds checkout_items view_history/;
977 # initialize our waiver hash with waiver IDs from hidden input
978 # (this ensures that we capture entries with no checked boxes)
979 foreach my $waiver_row_id ($self->cgi->param("waiver_id")) {
980 $waiver{$waiver_row_id} = {};
983 # process our waiver checkboxes into a hash, keyed by waiver ID
984 # (a new entry, if any, has id = 'new')
985 foreach my $waiver_type (@waiver_types) {
986 if ($self->cgi->param("waiver_$waiver_type")) {
987 foreach my $waiver_id ($self->cgi->param("waiver_$waiver_type")) {
988 # ensure this waiver exists in our hash
989 $waiver{$waiver_id} = {} if !$waiver{$waiver_id};
990 $waiver{$waiver_id}->{$waiver_type} = 1;
995 foreach my $k (keys %waiver) {
997 # get name from textbox
998 $w->{name} = $self->cgi->param("waiver_name_$k");
1000 foreach (@waiver_types) {
1001 $w->{$_} = 0 unless ($w->{$_});
1003 push @$saved_entries, $w;
1006 # update patron privacy waiver entries
1009 'open-ils.actor.patron.privacy_waiver.update',
1010 $self->editor->authtoken, undef, $saved_entries);
1012 $self->ctx->{updated_waiver_entries} = $saved_entries;
1015 # re-fetch user prefs
1016 return $self->_load_user_with_prefs || Apache2::Const::OK;
1019 sub load_myopac_prefs_my_lists {
1022 my @user_prefs = qw/
1024 opac.list_items_per_page
1027 my $stat = $self->_load_user_with_prefs;
1028 return $stat if $stat;
1030 return Apache2::Const::OK
1031 unless $self->cgi->request_method eq 'POST';
1034 my $set_map = $self->ctx->{user_setting_map};
1036 foreach my $key (@user_prefs) {
1037 my $val = $self->cgi->param($key);
1038 $settings{$key}= $val unless $$set_map{$key} eq $val;
1041 if (keys %settings) { # we found a different setting value
1042 # Send the modified settings off to be saved
1045 'open-ils.actor.patron.settings.update',
1046 $self->editor->authtoken, undef, \%settings);
1048 # re-fetch user prefs
1049 $self->ctx->{updated_user_settings} = \%settings;
1050 $stat = $self->_load_user_with_prefs;
1053 return $stat || Apache2::Const::OK;
1056 sub fetch_user_holds {
1058 my $hold_ids = shift;
1059 my $ids_only = shift;
1061 my $available = shift;
1065 my $e = $self->editor;
1066 my $all_ids; # to be used below.
1069 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1071 $hold_ids = $circ->request(
1072 'open-ils.circ.holds.id_list.retrieve.authoritative',
1079 $all_ids = $hold_ids;
1080 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
1083 $all_ids = $hold_ids;
1086 return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
1089 suppress_notices => 1,
1090 suppress_transits => 1,
1092 suppress_patron_details => 1
1095 # ----------------------------------------------------------------
1096 # Collect holds in batches of $batch_size for faster retrieval
1100 my $mk_req_batch = sub {
1102 my $top_idx = $batch_idx + $batch_size;
1103 while($batch_idx < $top_idx) {
1104 my $hold_id = $hold_ids->[$batch_idx++];
1105 last unless $hold_id;
1106 my $ses = OpenSRF::AppSession->create('open-ils.circ');
1107 my $req = $ses->request(
1108 'open-ils.circ.hold.details.retrieve',
1109 $e->authtoken, $hold_id, $args);
1110 push(@ses, {ses => $ses, req => $req});
1116 my(@collected, @holds, @ses);
1119 @ses = $mk_req_batch->() if $first;
1120 last if $first and not @ses;
1123 while(my $blob = pop(@collected)) {
1126 # in the holds edit UI, we need to know what formats and
1127 # languages the user selected for this hold, plus what
1128 # formats/langs are available on the MR as a whole.
1129 if ($blob->{hold}{hold}->hold_type eq 'M') {
1130 my $hold = $blob->{hold}->{hold};
1132 # for MR, fetch the combined MR unapi blob
1133 (undef, @data) = $self->get_records_and_facets(
1134 [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
1136 my $filter_org = $U->org_unit_ancestor_at_depth(
1137 $hold->selection_ou,
1138 $hold->selection_depth);
1140 my $filter_data = $U->simplereq(
1142 'open-ils.circ.mmr.holds.filters.authoritative.atomic',
1143 $hold->target, $filter_org, [$hold->id]
1146 $blob->{metarecord_filters} =
1147 $filter_data->[0]->{metarecord};
1148 $blob->{metarecord_selected_filters} =
1149 $filter_data->[1]->{hold};
1152 (undef, @data) = $self->get_records_and_facets(
1153 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
1157 $blob->{marc_xml} = $data[0]->{marc_xml};
1158 push(@holds, $blob);
1162 for my $req_data (@ses) {
1163 push(@collected, {hold => $req_data->{req}->gather(1)});
1164 $req_data->{ses}->kill_me;
1167 @ses = $mk_req_batch->();
1168 last unless @collected or @ses;
1172 # put the holds back into the original server sort order
1175 for my $id (@$hold_ids) {
1176 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1178 my $h = $sorted[-1]->{hold}->{hold};
1179 # if available, report the pickup lib in the list
1180 $pickup_libs{$h->pickup_lib} = 1 if (
1181 $h && $h->pickup_lib == $h->current_shelf_lib &&
1182 $h->shelf_time && !$h->cancel_time && !$h->fulfillment_time
1187 try { # if the service is not running, just let this fail silently
1188 $curbsides = $U->simplereq(
1189 'open-ils.curbside',
1190 'open-ils.curbside.fetch_mine.atomic',
1193 } catch Error with {};
1195 my @pickup_libs = sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } keys %pickup_libs;
1197 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, pickup_libs => \@pickup_libs, curbsides => $curbsides };
1200 sub handle_hold_update {
1203 my $hold_ids = shift;
1204 my $e = $self->editor;
1205 my $ctx = $self->ctx;
1208 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1209 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1211 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1213 if($action =~ /cancel/) {
1215 for my $hold_id (@hold_ids) {
1216 my $resp = $circ->request(
1217 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1220 } elsif ($action =~ /activate|suspend/) {
1223 for my $hold_id (@hold_ids) {
1224 my $vals = {id => $hold_id};
1226 if($action =~ /activate/) {
1227 $vals->{frozen} = 'f';
1228 $vals->{thaw_date} = undef;
1230 } elsif($action =~ /suspend/) {
1231 $vals->{frozen} = 't';
1232 # $vals->{thaw_date} = TODO;
1234 push(@$vlist, $vals);
1237 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1238 $self->ctx->{hold_suspend_post_capture} = 1 if
1239 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1241 } elsif ($action eq 'edit') {
1244 my $val = {"id" => $_};
1245 $val->{"frozen"} = $self->cgi->param("frozen");
1246 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1247 $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1248 $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1249 $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1250 $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1252 for my $field (qw/expire_time thaw_date/) {
1253 # XXX TODO make this support other date formats, not just
1255 next unless $self->cgi->param($field) =~
1256 m:^(\d{2})/(\d{2})/(\d{4})$:;
1257 $val->{$field} = "$3-$1-$2";
1260 $val->{holdable_formats} = # no-op for non-MR holds
1261 $self->compile_holdable_formats(undef, $_);
1267 'open-ils.circ.hold.update.batch.atomic',
1268 $e->authtoken, undef, \@vals
1269 )->gather(1); # LFW XXX test for failure
1270 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1271 foreach my $param (('loc', 'qtype', 'query')) {
1272 if ($self->cgi->param($param)) {
1273 my @vals = $self->cgi->param($param);
1274 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1277 } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1280 $circ = OpenSRF::AppSession->create('open-ils.curbside');
1282 # see what we're doing with curbside here...
1283 my $cs_action = $self->cgi->param("cs_action");
1284 my $slot_id = $self->cgi->param("cs_slot_id");
1286 # we have an id, let's grab it if we can
1287 my $slot = $e->retrieve_action_curbside($slot_id);
1288 $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1290 my $org = $self->cgi->param("cs_org");
1291 my $date = $self->cgi->param("cs_date");
1292 my $time = $self->cgi->param("cs_time");
1293 my $notes = $self->cgi->param("cs_notes");
1296 $org ||= $slot->org;
1297 $notes ||= $slot->notes;
1299 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1300 $date ||= $dt->strftime('%F');
1301 $time ||= $dt->strftime('%T');
1305 $ctx->{cs_org} = $org;
1306 $ctx->{cs_date} = $date;
1307 $ctx->{cs_time} = $time;
1308 $ctx->{cs_notes} = $notes;
1309 $ctx->{cs_slot_id} = $slot->id if ($slot);
1310 $ctx->{cs_slot} = $slot;
1312 if ($cs_action eq 'reset') {
1313 $ctx->{cs_org} = $org = undef;
1314 $ctx->{cs_date} = $date = undef;
1315 $ctx->{cs_time} = $time = undef;
1316 $ctx->{cs_notes} = $notes = undef;
1317 $ctx->{cs_slot_id} = $slot_id = undef;
1318 $ctx->{cs_slot} = $slot = undef;
1319 } elsif ($cs_action eq 'save' && $org && $date && $time) {
1320 my $mode = $slot ? 'update' : 'create';
1321 $slot = $circ->request(
1322 "open-ils.curbside.${mode}_appointment",
1323 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1326 if (defined $U->event_code($slot)) {
1327 $self->apache->log->warn(
1328 "error attempting to $mode a curbside appointment for patron ".
1329 $e->requestor->id . ", got event " . $slot->{textcode}
1331 $ctx->{curbside_action_event} = $slot;
1332 $ctx->{cs_slot} = undef;
1334 $ctx->{cs_slot} = $slot;
1336 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1337 } elsif ($cs_action eq 'cancel' && $slot) {
1338 my $curbsides = $U->simplereq(
1339 'open-ils.curbside',
1340 'open-ils.curbside.delete_appointment',
1341 $e->authtoken, $slot->id
1343 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1344 } elsif ($cs_action eq 'arrive' && $slot) {
1345 my $curbsides = $U->simplereq(
1346 'open-ils.curbside',
1347 'open-ils.curbside.mark_arrived',
1348 $e->authtoken, $slot->id
1350 } elsif ($cs_action eq 'deliver' && $slot) {
1351 my $curbsides = $U->simplereq(
1352 'open-ils.curbside',
1353 'open-ils.curbside.mark_delivered',
1354 $e->authtoken, $slot->id
1358 if ($date and $org and !$ctx->{cs_times}{$date}) {
1359 $ctx->{cs_times}{$date} = $circ->request(
1360 'open-ils.curbside.times_for_date.atomic',
1361 $e->authtoken, $date, $org
1367 return defined($url) ? $self->generic_redirect($url) : undef;
1370 sub load_myopac_holds {
1372 my $e = $self->editor;
1373 my $ctx = $self->ctx;
1375 my $limit = $self->cgi->param('limit') || 15;
1376 my $offset = $self->cgi->param('offset') || 0;
1377 my $action = $self->cgi->param('action') || '';
1378 my $hold_id = $self->cgi->param('hid');
1379 my $available = int($self->cgi->param('available') || 0);
1381 my $hold_handle_result;
1382 $hold_handle_result = $self->handle_hold_update($action) if $action;
1385 if ($self->cgi->param('sort') ne "") {
1386 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1389 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1392 if($holds_object->{holds}) {
1393 $ctx->{holds} = $holds_object->{holds};
1394 $ctx->{curbside_appointments} = {};
1396 $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1398 for my $cs (@{$holds_object->{curbsides}}) {
1400 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1401 $ctx->{cs_times}{$dt} = $U->simplereq(
1402 'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1403 $e->authtoken, $dt, $cs->org
1406 $ctx->{curbside_appointments}{$cs->org} = $cs;
1409 $ctx->{curbside_pickup_libs} = [];
1410 for my $pul (@{$holds_object->{pickup_libs}}) {
1411 push(@{$ctx->{curbside_pickup_libs}}, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1414 $ctx->{holds_ids} = $holds_object->{all_ids};
1415 $ctx->{holds_limit} = $limit;
1416 $ctx->{holds_offset} = $offset;
1418 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1423 sub load_place_hold {
1425 my $ctx = $self->ctx;
1426 my $gos = $ctx->{get_org_setting};
1427 my $e = $self->editor;
1428 my $cgi = $self->cgi;
1430 $self->ctx->{page} = 'place_hold';
1431 my @targets = uniq $cgi->param('hold_target');
1432 my @parts = $cgi->param('part');
1434 $ctx->{hold_type} = $cgi->param('hold_type');
1435 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1436 $ctx->{email_notify} = $cgi->param('email_notify');
1437 if ($cgi->param('phone_notify_checkbox')) {
1438 $ctx->{phone_notify} = $cgi->param('phone_notify');
1440 if ($cgi->param('sms_notify_checkbox')) {
1441 $ctx->{sms_notify} = $cgi->param('sms_notify');
1442 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1445 return $self->generic_redirect unless @targets;
1447 # Check for multiple hold placement via the num_copies widget.
1448 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1449 if ($num_copies > 1) {
1450 # Only if we have 1 hold target and no parts.
1451 if (scalar(@targets) == 1 && !$parts[0]) {
1452 # Also, only for M and T holds.
1453 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1454 # Add the extra holds to @targets. NOTE: We start with
1455 # 1 and go to < $num_copies to account for the
1457 for (my $i = 1; $i < $num_copies; $i++) {
1458 push(@targets, $targets[0]);
1464 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1466 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1471 au => ['settings', 'card']
1474 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1475 my $user_setting_map = {
1476 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1478 $ctx->{staff_recipient}->settings
1481 $ctx->{user_setting_map} = $user_setting_map;
1483 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1484 if ($default_notify =~ /email/) {
1485 $ctx->{default_email_notify} = 'checked';
1487 $ctx->{default_email_notify} = '';
1489 if ($default_notify =~ /phone/) {
1490 $ctx->{default_phone_notify} = 'checked';
1492 $ctx->{default_phone_notify} = '';
1494 if ($default_notify =~ /sms/) {
1495 $ctx->{default_sms_notify} = 'checked';
1497 $ctx->{default_sms_notify} = '';
1499 if ($cgi->param('hold_suspend')) {
1501 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1502 # We should use a date input type on the forms once it is supported by Firefox.
1503 # I didn't do that now because it is not available in a general release.
1504 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1506 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1507 $ctx->{thaw_date} = $dt->ymd;
1510 $logger->warn("ignoring invalid thaw_date when placing hold request");
1516 # If we have a default pickup location, grab it
1517 if ($$user_setting_map{'opac.default_pickup_location'}) {
1518 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1521 my $request_lib = $e->requestor->ws_ou;
1523 $ctx->{hold_data} = \@hold_data;
1525 $data_filler = sub {
1527 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1528 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1529 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1530 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1531 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1532 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1536 my $type_dispatch = {
1538 # target metarecords
1539 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1541 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1545 for my $id (@targets) {
1546 my ($mr) = grep {$_->id eq $id} @$mrecs;
1548 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1549 my $filter_data = $U->simplereq(
1551 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1553 my $holdable_formats =
1554 $self->compile_holdable_formats($mr->id);
1556 push(@hold_data, $data_filler->({
1558 record => $mr->master_record,
1559 holdable_formats => $holdable_formats,
1560 metarecord_filters => $filter_data->{metarecord}
1565 my $recs = $e->batch_retrieve_biblio_record_entry(
1566 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1570 for my $id (@targets) { # force back into the correct order
1571 my ($rec) = grep {$_->id eq $id} @$recs;
1573 # NOTE: if tpac ever supports locked-down pickup libs,
1574 # we'll need to pass a pickup_lib param along with the
1575 # record to filter the set of monographic parts.
1576 my $parts = $U->simplereq(
1578 'open-ils.search.biblio.record_hold_parts',
1579 {record => $rec->id}
1582 # T holds on records that have parts are OK, but if the record has
1583 # no non-part copies, the hold will ultimately fail. When that
1584 # happens, require the user to select a part.
1585 my $part_required = 0;
1587 my $np_copies = $e->json_query({
1588 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1589 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1591 '+acp' => {deleted => 'f'},
1592 '+acn' => {deleted => 'f', record => $rec->id},
1593 '+acpm' => {id => undef}
1596 $part_required = 1 if $np_copies->[0]->{count} == 0;
1599 push(@hold_data, $data_filler->({
1603 part_required => $part_required
1608 my $vols = $e->batch_retrieve_asset_call_number([
1611 "flesh_fields" => {"acn" => ["record"]}
1613 ], {substream => 1});
1615 for my $id (@targets) {
1616 my ($vol) = grep {$_->id eq $id} @$vols;
1617 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1621 my $copies = $e->batch_retrieve_asset_copy([
1625 "acn" => ["record"],
1626 "acp" => ["call_number"]
1629 ], {substream => 1});
1631 for my $id (@targets) {
1632 my ($copy) = grep {$_->id eq $id} @$copies;
1633 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1637 my $isses = $e->batch_retrieve_serial_issuance([
1641 "siss" => ["subscription"], "ssub" => ["record_entry"]
1644 ], {substream => 1});
1646 for my $id (@targets) {
1647 my ($iss) = grep {$_->id eq $id} @$isses;
1648 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1653 }->{$ctx->{hold_type}}->();
1655 # caller sent bad target IDs or the wrong hold type
1656 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1658 # generate the MARC xml for each record
1659 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1661 my $pickup_lib = $cgi->param('pickup_lib');
1662 # no pickup lib means no holds placement
1663 return Apache2::Const::OK unless $pickup_lib;
1665 $ctx->{hold_attempt_made} = 1;
1667 # Give the original CGI params back to the user in case they
1668 # want to try to override something.
1669 $ctx->{orig_params} = $cgi->Vars;
1670 delete $ctx->{orig_params}{submit};
1671 delete $ctx->{orig_params}{hold_target};
1672 delete $ctx->{orig_params}{part};
1674 my $usr = $e->requestor->id;
1676 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1677 # find the real hold target
1679 $usr = $U->simplereq(
1681 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1682 $e->authtoken, $cgi->param("hold_usr"));
1684 if (defined $U->event_code($usr)) {
1685 $ctx->{hold_failed} = 1;
1686 $ctx->{hold_failed_event} = $usr;
1690 # target_id is the true target_id for holds placement.
1691 # needed for attempt_hold_placement()
1692 # With the exception of P-type holds, target_id == target->id.
1693 $_->{target_id} = $_->{target}->id for @hold_data;
1695 if ($ctx->{hold_type} eq 'T') {
1697 # Much like quantum wave-particles, P-type holds pop into
1698 # and out of existence at the user's whim. For our purposes,
1699 # we treat such holds as T(itle) holds with a selected_part
1700 # designation. When the time comes to pass the hold information
1701 # off for holds possibility testing and placement, make it look
1702 # like a real P-type hold.
1703 my (@p_holds, @t_holds);
1705 # Now that we have the num_copies field for mutliple title and
1706 # metarecord hold placement, the number of holds and parts
1707 # arrays can get out of sync. We only want to parse out parts
1708 # if the numbers are equal.
1709 if ($#hold_data == $#parts) {
1710 for my $idx (0..$#parts) {
1711 my $hdata = $hold_data[$idx];
1712 if (my $part = $parts[$idx]) {
1713 $hdata->{target_id} = $part;
1714 $hdata->{selected_part} = $part;
1715 push(@p_holds, $hdata);
1717 push(@t_holds, $hdata);
1721 @t_holds = @hold_data;
1724 $self->apache->log->warn("$#parts : @t_holds");
1726 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1727 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1730 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1733 # NOTE: we are leaving the staff-placed patron barcode cookie
1734 # in place. Otherwise, it's not possible to place more than
1735 # one hold for the patron within a staff/patron session. This
1736 # does leave the barcode to linger longer than is ideal, but
1737 # normal staff work flow will cause the cookie to be replaced
1738 # with each new patron anyway.
1739 # TODO: See about getting the staff client to clear the cookie
1741 # return to the place_hold page so the results of the hold
1742 # placement attempt can be reported to the user
1743 return Apache2::Const::OK;
1746 sub attempt_hold_placement {
1747 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1748 my $cgi = $self->cgi;
1749 my $ctx = $self->ctx;
1750 my $e = $self->editor;
1752 # First see if we should warn/block for any holds that
1753 # might have locally available items.
1754 for my $hdata (@hold_data) {
1755 my ($local_block, $local_alert) = $self->local_avail_concern(
1756 $hdata->{target_id}, $hold_type, $pickup_lib);
1759 $hdata->{hold_failed} = 1;
1760 $hdata->{hold_local_block} = 1;
1761 } elsif ($local_alert) {
1762 $hdata->{hold_failed} = 1;
1763 $hdata->{hold_local_alert} = 1;
1767 my $method = 'open-ils.circ.holds.test_and_create.batch';
1769 if ($cgi->param('override')) {
1770 $method .= '.override';
1772 } elsif (!$ctx->{is_staff}) {
1774 $method .= '.override' if $self->ctx->{get_org_setting}->(
1775 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1778 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1781 if(@create_targets) {
1783 # holdable formats may be different for each MR hold.
1784 # map each set to the ID of the target.
1785 my $holdable_formats = {};
1786 if ($hold_type eq 'M') {
1787 $holdable_formats->{$_->{target_id}} =
1788 $_->{holdable_formats} for @hold_data;
1791 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1792 my $breq = $bses->request(
1797 pickup_lib => $pickup_lib,
1798 hold_type => $hold_type,
1799 holdable_formats_map => $holdable_formats,
1804 while (my $resp = $breq->recv) {
1806 $resp = $resp->content;
1807 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1809 if ($U->event_code($resp)) {
1810 $ctx->{general_hold_error} = $resp;
1814 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1815 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1816 my $result = $resp->{result};
1818 if ($U->event_code($result)) {
1819 # e.g. permission denied
1820 $hdata->{hold_failed} = 1;
1821 $hdata->{hold_failed_event} = $result;
1825 if(not ref $result and $result > 0) {
1826 # successul hold returns the hold ID
1828 $hdata->{hold_success} = $result;
1831 # hold-specific failure event
1832 $hdata->{hold_failed} = 1;
1834 if (ref $result eq 'HASH') {
1835 $hdata->{hold_failed_event} = $result->{last_event};
1837 if ($result->{age_protected_copy}) {
1838 my %temp = %{$hdata->{hold_failed_event}};
1839 my $theTextcode = $temp{"textcode"};
1840 $theTextcode.=".override";
1841 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1842 $hdata->{age_protect} = 1;
1844 $hdata->{could_override} = $result->{place_unfillable} ||
1845 $self->test_could_override($hdata->{hold_failed_event});
1847 } elsif (ref $result eq 'ARRAY') {
1848 $hdata->{hold_failed_event} = $result->[0];
1850 if ($result->[3]) { # age_protect_only
1851 my %temp = %{$hdata->{hold_failed_event}};
1852 my $theTextcode = $temp{"textcode"};
1853 $theTextcode.=".override";
1854 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1855 $hdata->{age_protect} = 1;
1857 $hdata->{could_override} = $result->[4] || # place_unfillable
1858 $self->test_could_override($hdata->{hold_failed_event});
1868 if ($self->cgi->param('clear_cart')) {
1869 $self->clear_anon_cache;
1873 # pull the selected formats and languages for metarecord holds
1874 # from the CGI params and map them into the JSON holdable
1875 # formats...er, format.
1876 # if no metarecord is provided, we'll pull it from the target
1877 # of the provided hold.
1878 sub compile_holdable_formats {
1879 my ($self, $mr_id, $hold_id) = @_;
1880 my $e = $self->editor;
1881 my $cgi = $self->cgi;
1883 # exit early if not needed
1885 grep /metarecord_formats_|metarecord_langs_/,
1888 # CGI params are based on the MR id, since during hold placement
1889 # we have no old ID. During hold edit, map the hold ID back to
1890 # the metarecod target.
1892 $e->retrieve_action_hold_request($hold_id)->target
1895 my $format_attr = $self->ctx->{get_cgf}->(
1896 'opac.metarecord.holds.format_attr');
1898 if (!$format_attr) {
1899 $logger->error("Missing config.global_flag: ".
1900 "opac.metarecord.holds.format_attr!");
1904 $format_attr = $format_attr->value;
1906 # during hold placement or edit submission, the user selects
1907 # which of the available formats/langs are acceptable.
1908 # Capture those here as the holdable_formats for the MR hold.
1909 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1910 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1912 # map the selected attrs into the JSON holdable_formats structure
1914 if (@selected_formats) {
1916 map { {_attr => $format_attr, _val => $_} }
1920 if (@selected_langs) {
1922 map { {_attr => 'item_lang', _val => $_} }
1927 return OpenSRF::Utils::JSON->perl2JSON($blob);
1930 sub fetch_user_circs {
1932 my $flesh = shift; # flesh bib data, etc.
1933 my $circ_ids = shift;
1937 my $e = $self->editor;
1942 @circ_ids = @$circ_ids;
1947 select => {circ => ['id']},
1951 usr => $e->requestor->id,
1952 checkin_time => undef,
1954 {stop_fines => undef},
1955 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1959 order_by => {circ => ['due_date']}
1962 $query->{limit} = $limit if $limit;
1963 $query->{offset} = $offset if $offset;
1965 my $ids = $e->json_query($query);
1966 @circ_ids = map {$_->{id}} @$ids;
1969 return [] unless @circ_ids;
1974 circ => ['target_copy'],
1975 acp => ['call_number'],
1976 acn => ['record','owning_lib']
1981 my $circs = $e->search_action_circulation(
1982 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1985 for my $circ (@$circs) {
1988 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1989 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1990 undef # pre-cat copy, use the dummy title/author instead
1995 # make sure the final list is in the correct order
1997 for my $id (@circ_ids) {
2000 (grep { $_->{circ}->id == $id } @circs)
2004 return \@sorted_circs;
2008 sub handle_circ_renew {
2011 my $ctx = $self->ctx;
2013 my @renew_ids = $self->cgi->param('circ');
2015 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2017 # TODO: fire off renewal calls in batches to speed things up
2019 for my $circ (@$circs) {
2021 my $evt = $U->simplereq(
2023 'open-ils.circ.renew',
2024 $self->editor->authtoken,
2026 patron_id => $self->editor->requestor->id,
2027 copy_id => $circ->{circ}->target_copy,
2032 # TODO return these, then insert them into the circ data
2033 # blob that is shoved into the template for each circ
2034 # so the template won't have to match them
2035 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2041 sub load_myopac_circs {
2043 my $e = $self->editor;
2044 my $ctx = $self->ctx;
2047 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2048 my $offset = $self->cgi->param('offset') || 0;
2049 my $action = $self->cgi->param('action') || '';
2051 # perform the renewal first if necessary
2052 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2054 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2056 my $success_renewals = 0;
2057 my $failed_renewals = 0;
2058 for my $data (@{$ctx->{circs}}) {
2059 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2062 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2064 # extract the fail_part, if present, from the event payload;
2065 # since # the payload is an acp object in some cases,
2066 # blindly looking for a # 'fail_part' key in the template can
2068 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2069 $evt->{payload}->{fail_part} :
2072 $data->{renewal_response} = $evt;
2073 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2074 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2078 $ctx->{success_renewals} = $success_renewals;
2079 $ctx->{failed_renewals} = $failed_renewals;
2081 return Apache2::Const::OK;
2084 sub load_myopac_circ_history {
2086 my $e = $self->editor;
2087 my $ctx = $self->ctx;
2088 my $limit = $self->cgi->param('limit') || 15;
2089 my $offset = $self->cgi->param('offset') || 0;
2090 my $action = $self->cgi->param('action') || '';
2092 my $circ_handle_result;
2093 $circ_handle_result = $self->handle_circ_update($action) if $action;
2095 $ctx->{circ_history_limit} = $limit;
2096 $ctx->{circ_history_offset} = $offset;
2098 # Defer limitation to circ_history.tt2 when sorting
2099 if ($self->cgi->param('sort')) {
2104 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2105 return Apache2::Const::OK;
2108 # if 'flesh' is set, copy data etc. is loaded and the return value is
2109 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2111 sub fetch_user_circ_history {
2112 my ($self, $flesh, $limit, $offset) = @_;
2113 my $e = $self->editor;
2116 $limits{offset} = $offset if defined $offset;
2117 $limits{limit} = $limit if defined $limit;
2122 auch => ['target_copy','source_circ'],
2123 acp => ['call_number'],
2129 my $circs = $e->search_action_user_circ_history(
2131 {usr => $e->requestor->id},
2132 { # order newest to oldest by default
2133 order_by => {auch => 'xact_start DESC'},
2134 $flesh ? %flesh_ops : (),
2142 return $circs unless $flesh;
2146 my %unapi_cache = ();
2147 for my $circ (@$circs) {
2148 if ($circ->target_copy->call_number->id == -1) {
2151 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2155 my $bre_id = $circ->target_copy->call_number->record->id;
2157 if (exists $unapi_cache{$bre_id}) {
2158 $unapi = $unapi_cache{$bre_id};
2160 my $result = $e->json_query({
2162 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2166 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2177 marc_xml => undef # failed, but try to go on
2186 sub handle_circ_update {
2189 my $circ_ids = shift;
2191 $circ_ids //= [$self->cgi->param('circ_id')];
2193 if ($action =~ /delete/) {
2195 circ_ids => $circ_ids,
2200 'open-ils.actor.history.circ.clear',
2201 $self->editor->authtoken,
2209 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2210 sub load_myopac_hold_history {
2212 my $e = $self->editor;
2213 my $ctx = $self->ctx;
2214 my $limit = $self->cgi->param('limit') || 15;
2215 my $offset = $self->cgi->param('offset') || 0;
2216 $ctx->{hold_history_limit} = $limit;
2217 $ctx->{hold_history_offset} = $offset;
2219 my $hold_ids = $e->json_query({
2223 transform => 'action.usr_visible_holds',
2224 result_field => 'id'
2228 where => {id => $e->requestor->id}
2231 # This is used to detect whether we want to show the curbside tab
2232 my $extant_holds_object = $self->fetch_user_holds();
2233 if($extant_holds_object->{holds}) {
2234 $ctx->{curbside_pickup_libs} = [];
2235 for my $pul (@{$extant_holds_object->{pickup_libs}}) {
2236 push(@{$ctx->{curbside_pickup_libs}}, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
2240 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2241 if($holds_object->{holds}) {
2242 $ctx->{holds} = $holds_object->{holds};
2244 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2246 return Apache2::Const::OK;
2249 sub load_myopac_payment_form {
2253 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
2254 $r = $self->prepare_extended_user_info and return $r;
2256 return Apache2::Const::OK;
2259 # TODO: add other filter options as params/configs/etc.
2260 sub load_myopac_payments {
2262 my $limit = $self->cgi->param('limit') || 20;
2263 my $offset = $self->cgi->param('offset') || 0;
2264 my $e = $self->editor;
2266 $self->ctx->{payment_history_limit} = $limit;
2267 $self->ctx->{payment_history_offset} = $offset;
2270 $args->{limit} = $limit if $limit;
2271 $args->{offset} = $offset if $offset;
2273 if (my $max_age = $self->ctx->{get_org_setting}->(
2274 $e->requestor->home_ou, "opac.payment_history_age_limit"
2276 my $min_ts = DateTime->now(
2277 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2278 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2280 $logger->info("XXX min_ts: $min_ts");
2281 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2284 $self->ctx->{payments} = $U->simplereq(
2286 'open-ils.actor.user.payments.retrieve.atomic',
2287 $e->authtoken, $e->requestor->id, $args);
2289 return Apache2::Const::OK;
2292 # 1. caches the form parameters
2293 # 2. loads the credit card payment "Processing..." page
2294 sub load_myopac_pay_init {
2296 my $cache = OpenSRF::Utils::Cache->new('global');
2298 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2300 if (!@payment_xacts) {
2301 # for consistency with load_myopac_payment_form() and
2302 # to preserve backwards compatibility, if no xacts are
2303 # selected, assume all (applicable) transactions are wanted.
2304 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2305 return $stat if $stat;
2307 map { $_->{xact}->id } (
2308 @{$self->ctx->{fines}->{circulation}},
2309 @{$self->ctx->{fines}->{grocery}}
2313 return $self->generic_redirect unless @payment_xacts;
2315 my $cc_args = {"where_process" => 1};
2317 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2318 number cvv2 expire_year expire_month billing_first
2319 billing_last billing_address billing_city billing_state
2320 billing_zip stripe_token
2324 cc_args => $cc_args,
2325 user => $self->ctx->{user}->id,
2326 xacts => \@payment_xacts
2329 # generate a temporary cache token and cache the form data
2330 my $token = md5_hex($$ . time() . rand());
2331 $cache->put_cache($token, $cache_args, 30);
2333 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2335 # after we render the processing page, we quickly redirect to submit
2336 # the actual payment. The refresh url contains the payment token.
2337 # It also contains the list of xact IDs, which allows us to clear the
2338 # cache at the earliest possible time while leaving a trace of which
2339 # transactions we were processing, so the UI can bring the user back
2340 # to the payment form w/ the same xacts if the payment fails.
2342 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2343 $refresh .= ";xact=$_" for @payment_xacts;
2344 $self->ctx->{refresh} = $refresh;
2346 return Apache2::Const::OK;
2349 # retrieve the cached CC payment info and send off for processing
2350 sub load_myopac_pay {
2352 my $token = $self->ctx->{page_args}->[0];
2353 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2355 my $cache = OpenSRF::Utils::Cache->new('global');
2356 my $cache_args = $cache->get_cache($token);
2357 $cache->delete_cache($token);
2359 # this page is loaded immediately after the token is created.
2360 # if the cached data is not there, it's because of an invalid
2361 # token (or cache failure) and not because of a timeout.
2362 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2364 my @payment_xacts = @{$cache_args->{xacts}};
2365 my $cc_args = $cache_args->{cc_args};
2367 # as an added security check, verify the user submitting
2368 # the form is the same as the user whose data was cached
2369 return Apache2::Const::HTTP_BAD_REQUEST unless
2370 $cache_args->{user} == $self->ctx->{user}->id;
2372 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2375 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2377 # balance_owed is computed specifically from the fines we're paying
2378 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2379 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2380 return Apache2::Const::HTTP_BAD_REQUEST;
2384 "cc_args" => $cc_args,
2385 "userid" => $self->ctx->{user}->id,
2386 "payment_type" => "credit_card_payment",
2387 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2390 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2391 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2394 $self->ctx->{"payment_response"} = $resp;
2396 unless ($resp->{"textcode"}) {
2397 $self->ctx->{printable_receipt} = $U->simplereq(
2398 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2399 $self->editor->authtoken, $resp->{payments}
2403 return Apache2::Const::OK;
2406 sub load_myopac_receipt_print {
2409 $self->ctx->{printable_receipt} = $U->simplereq(
2410 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2411 $self->editor->authtoken, [$self->cgi->param("payment")]
2414 return Apache2::Const::OK;
2417 sub load_myopac_receipt_email {
2420 # The following ML method doesn't actually check whether the user in
2421 # question has an email address, so we do.
2422 if ($self->ctx->{user}->email) {
2423 $self->ctx->{email_receipt_result} = $U->simplereq(
2424 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2425 $self->editor->authtoken, [$self->cgi->param("payment")]
2428 $self->ctx->{email_receipt_result} =
2429 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2432 return Apache2::Const::OK;
2436 my ($self, $limit, $offset, $id_list) = @_;
2438 # XXX TODO: check for failure after various network calls
2440 # It may be unclear, but this result structure lumps circulation and
2441 # reservation fines together, and keeps grocery fines separate.
2442 $self->ctx->{"fines"} = {
2443 "circulation" => [],
2450 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2452 # TODO: This should really be a ML call, but the existing calls
2453 # return an excessive amount of data and don't offer streaming
2455 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2457 my $req = $cstore->request(
2458 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2460 usr => $self->editor->requestor->id,
2461 balance_owed => {'!=' => 0},
2462 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2467 mobts => [qw/grocery circulation reservation/],
2468 bresv => ['target_resource_type'],
2472 circ => ['target_copy'],
2473 acp => ['call_number'],
2476 order_by => { mobts => 'xact_start' },
2481 # Collect $$ amounts from each transaction for summing below.
2482 my (@paid_amounts, @owed_amounts, @balance_amounts);
2484 while(my $resp = $req->recv) {
2485 my $mobts = $resp->content;
2486 my $circ = $mobts->circulation;
2489 if($mobts->grocery) {
2490 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2491 $last_billing = pop(@billings);
2494 push(@paid_amounts, $mobts->total_paid);
2495 push(@owed_amounts, $mobts->total_owed);
2496 push(@balance_amounts, $mobts->balance_owed);
2498 my $marc_xml = undef;
2499 if ($mobts->xact_type eq 'reservation' and
2500 $mobts->reservation->target_resource_type->record) {
2501 $marc_xml = XML::LibXML->new->parse_string(
2502 $mobts->reservation->target_resource_type->record->marc
2504 } elsif ($mobts->xact_type eq 'circulation' and
2505 $circ->target_copy->call_number->id != -1) {
2506 $marc_xml = XML::LibXML->new->parse_string(
2507 $circ->target_copy->call_number->record->marc
2512 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2515 last_grocery_billing => $last_billing,
2516 marc_xml => $marc_xml
2523 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2524 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2525 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2530 sub prepare_fines_for_payment {
2531 # This assumes $self->prepare_fines has already been run
2535 if ($self->ctx->{fines}) {
2536 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2537 @{$self->ctx->{fines}->{circulation}},
2538 @{$self->ctx->{fines}->{grocery}}
2545 sub load_myopac_main {
2547 my $limit = $self->cgi->param('limit') || 0;
2548 my $offset = $self->cgi->param('offset') || 0;
2549 $self->ctx->{search_ou} = $self->_get_search_lib();
2550 $self->ctx->{user}->notes(
2551 $self->editor->search_actor_usr_note({
2552 usr => $self->ctx->{user}->id,
2556 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2559 sub load_myopac_update_email {
2561 my $e = $self->editor;
2562 my $ctx = $self->ctx;
2563 my $email = $self->cgi->param('email') || '';
2564 my $current_pw = $self->cgi->param('current_pw') || '';
2566 # needed for most up-to-date email address
2567 if (my $r = $self->prepare_extended_user_info) { return $r };
2569 return Apache2::Const::OK
2570 unless $self->cgi->request_method eq 'POST';
2572 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2573 $ctx->{invalid_email} = $email;
2574 return Apache2::Const::OK;
2577 my $stat = $U->simplereq(
2579 'open-ils.actor.user.email.update',
2580 $e->authtoken, $email, $current_pw);
2582 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2583 $ctx->{password_incorrect} = 1;
2584 return Apache2::Const::OK;
2587 unless ($self->cgi->param("redirect_to")) {
2588 my $url = $self->apache->unparsed_uri;
2589 $url =~ s/update_email/prefs/;
2591 return $self->generic_redirect($url);
2594 return $self->generic_redirect;
2597 sub load_myopac_update_username {
2599 my $e = $self->editor;
2600 my $ctx = $self->ctx;
2601 my $username = $self->cgi->param('username') || '';
2602 my $current_pw = $self->cgi->param('current_pw') || '';
2604 $self->prepare_extended_user_info;
2606 my $allow_change = 1;
2608 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2609 if(defined($lock_usernames) and $lock_usernames == 1) {
2610 # Policy says no username changes
2613 # We want this further down.
2614 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2615 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2616 if(!$username_unlimit) {
2618 # Default is "starts with a number"
2619 $regex_check = '^\d+';
2621 # You already have a username?
2622 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2627 if(!$allow_change) {
2628 my $url = $self->apache->unparsed_uri;
2629 $url =~ s/update_username/prefs/;
2631 return $self->generic_redirect($url);
2634 return Apache2::Const::OK
2635 unless $self->cgi->request_method eq 'POST';
2637 unless($username and $username !~ /\s/) { # any other username restrictions?
2638 $ctx->{invalid_username} = $username;
2639 return Apache2::Const::OK;
2642 # New username can't look like a barcode if we have a barcode regex
2643 if($regex_check and $username =~ /$regex_check/) {
2644 $ctx->{invalid_username} = $username;
2645 return Apache2::Const::OK;
2648 # New username has to look like a username if we have a username regex
2649 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2650 if($regex_check and $username !~ /$regex_check/) {
2651 $ctx->{invalid_username} = $username;
2652 return Apache2::Const::OK;
2655 if($username ne $e->requestor->usrname) {
2657 my $evt = $U->simplereq(
2659 'open-ils.actor.user.username.update',
2660 $e->authtoken, $username, $current_pw);
2662 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2663 $ctx->{password_incorrect} = 1;
2664 return Apache2::Const::OK;
2667 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2668 $ctx->{username_exists} = $username;
2669 return Apache2::Const::OK;
2673 my $url = $self->apache->unparsed_uri;
2674 $url =~ s/update_username/prefs/;
2676 return $self->generic_redirect($url);
2679 sub load_myopac_update_password {
2681 my $e = $self->editor;
2682 my $ctx = $self->ctx;
2684 return Apache2::Const::OK
2685 unless $self->cgi->request_method eq 'POST';
2687 my $current_pw = $self->cgi->param('current_pw') || '';
2688 my $new_pw = $self->cgi->param('new_pw') || '';
2689 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2691 unless($new_pw eq $new_pw2) {
2692 $ctx->{password_nomatch} = 1;
2693 return Apache2::Const::OK;
2696 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2699 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2700 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2703 if($pw_regex and $new_pw !~ /$pw_regex/) {
2704 $ctx->{password_invalid} = 1;
2705 return Apache2::Const::OK;
2708 my $evt = $U->simplereq(
2710 'open-ils.actor.user.password.update',
2711 $e->authtoken, $new_pw, $current_pw);
2714 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2715 $ctx->{password_incorrect} = 1;
2716 return Apache2::Const::OK;
2719 my $url = $self->apache->unparsed_uri;
2720 $url =~ s/update_password/prefs/;
2722 return $self->generic_redirect($url);
2725 sub _update_bookbag_metadata {
2726 my ($self, $bookbag) = @_;
2728 $bookbag->name($self->cgi->param("name"));
2729 $bookbag->description($self->cgi->param("description"));
2731 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2735 sub _get_lists_per_page {
2738 if($self->editor->requestor) {
2739 $self->timelog("Checking for opac.lists_per_page preference");
2740 # See if the user has a lists per page preference
2741 my $ipp = $self->editor->search_actor_user_setting({
2742 usr => $self->editor->requestor->id,
2743 name => 'opac.lists_per_page'
2745 $self->timelog("Got opac.lists_per_page preference");
2746 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2748 return 10; # default
2751 sub _get_items_per_page {
2754 if($self->editor->requestor) {
2755 $self->timelog("Checking for opac.list_items_per_page preference");
2756 # See if the user has a list items per page preference
2757 my $ipp = $self->editor->search_actor_user_setting({
2758 usr => $self->editor->requestor->id,
2759 name => 'opac.list_items_per_page'
2761 $self->timelog("Got opac.list_items_per_page preference");
2762 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2764 return 10; # default
2767 sub load_myopac_bookbags {
2769 my $e = $self->editor;
2770 my $ctx = $self->ctx;
2771 my $limit = $self->_get_lists_per_page || 10;
2772 my $offset = $self->cgi->param('offset') || 0;
2774 $ctx->{bookbags_limit} = $limit;
2775 $ctx->{bookbags_offset} = $offset;
2777 # for list item pagination
2778 my $item_limit = $self->_get_items_per_page;
2779 my $item_page = $self->cgi->param('item_page') || 1;
2780 my $item_offset = ($item_page - 1) * $item_limit;
2781 $ctx->{bookbags_item_page} = $item_page;
2783 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2784 $e->xact_begin; # replication...
2786 my $rv = $self->load_mylist;
2787 unless($rv eq Apache2::Const::OK) {
2792 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2794 {owner => $e->requestor->id, btype => 'bookbag'}, {
2795 order_by => {cbreb => 'name'},
2803 if(!$ctx->{bookbags}) {
2805 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2808 # We load the user prefs to get their default bookbag.
2809 $self->_load_user_with_prefs;
2811 # We also want a total count of the user's bookbags.
2813 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2815 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2817 my $r = $e->json_query($q);
2818 $ctx->{bookbag_count} = $r->[0]->{'count'};
2820 # If the user wants a specific bookbag's items, load them.
2822 if ($self->cgi->param("bbid")) {
2824 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2827 my $query = $self->_prepare_bookbag_container_query(
2828 $bookbag->id, $sorter, $modifier
2831 # Calculate total count of the items in selected bookbag.
2832 # This total includes record entries that have no assets available.
2833 my $bb_search_results = $U->simplereq(
2834 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2835 {"limit" => 1, "offset" => 0}, $query
2836 ); # we only need the count, so do the actual search with limit=1
2838 if ($bb_search_results) {
2839 $ctx->{bb_item_count} = $bb_search_results->{count};
2841 $logger->warn("search failed in load_myopac_bookbags()");
2842 $ctx->{bb_item_count} = 0; # fallback value
2845 #calculate page count
2846 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2848 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2849 if (!$self->_update_bookbag_metadata($bookbag)) {
2851 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2854 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2857 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2858 if ($self->cgi->param($param)) {
2859 my @vals = $self->cgi->param($param);
2860 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2864 return $self->generic_redirect($url);
2868 # we're done with our CStoreEditor. Rollback here so
2869 # later calls don't cause a timeout, resulting in a
2870 # transaction rollback under the covers.
2874 # For list items pagination
2876 "limit" => $item_limit,
2877 "offset" => $item_offset
2880 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2881 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2883 # capture pref_ou for callnumber filter/display
2884 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2886 # search for local callnumbers for display
2887 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2889 my (undef, @recs) = $self->get_records_and_facets(
2890 [ map {$_->target_biblio_record_entry->id} @$items ],
2893 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2895 site => $ctx->{get_aou}->($focus_ou)->shortname,
2896 pref_lib => $ctx->{pref_ou}
2900 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2902 $bookbag->items($items);
2906 # If we have add_rec, we got here from the "Add to new list"
2907 # or "See all" popmenu items.
2908 if (my $add_rec = $self->cgi->param('add_rec')) {
2909 $self->ctx->{add_rec} = $add_rec;
2910 # But not in the staff client, 'cause that breaks things.
2911 unless ($self->ctx->{is_staff}) {
2912 # allow caller to provide the where_from in cases where
2913 # the referer is an intermediate error page
2914 if ($self->cgi->param('where_from')) {
2915 $self->ctx->{where_from} = $self->cgi->param('where_from');
2917 $self->ctx->{where_from} = $self->ctx->{referer};
2918 if ( my $anchor = $self->cgi->param('anchor') ) {
2919 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2925 # this rollback may be a dupe, but that's OK because
2926 # cstoreditor ignores dupe rollbacks
2929 return Apache2::Const::OK;
2933 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
2934 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2935 sub load_myopac_bookbag_update {
2936 my ($self, $action, $list_id, @hold_recs) = @_;
2937 my $e = $self->editor;
2938 my $cgi = $self->cgi;
2940 # save_notes is effectively another action, but is passed in a separate
2941 # CGI parameter for what are really just layout reasons.
2942 $action = 'save_notes' if $cgi->param('save_notes');
2943 $action ||= $cgi->param('action');
2945 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2947 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2948 my @selected_item = $cgi->param('selected_item');
2949 my $shared = $cgi->param('shared');
2950 my $move_cart = $cgi->param('move_cart');
2951 my $name = $cgi->param('name');
2952 my $description = $cgi->param('description');
2956 # bail out if user is attempting an action that requires
2957 # that at least one list item be selected
2958 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
2959 ($action eq 'place_hold' || $action eq 'print' ||
2960 $action eq 'email' || $action eq 'del_item')) {
2961 my $url = $self->ctx->{referer};
2962 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
2963 return $self->generic_redirect($url);
2966 # This url intentionally leaves off the edit_notes parameter, but
2967 # may need to add some back in for paging.
2969 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2970 $self->ctx->{opac_root} . "/myopac/lists?";
2972 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2973 if ($cgi->param($param)) {
2974 my @vals = $cgi->param($param);
2975 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2979 if ($action eq 'create') {
2982 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2984 $list->description($description);
2985 $list->owner($e->requestor->id);
2986 $list->btype('bookbag');
2987 $list->pub($shared ? 't' : 'f');
2988 $success = $U->simplereq('open-ils.actor',
2989 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2990 if (ref($success) ne 'HASH') {
2991 $list_id = (ref($success)) ? $success->id : $success;
2992 if (scalar @add_rec) {
2993 foreach my $add_rec (@add_rec) {
2994 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2995 $item->bucket($list_id);
2996 $item->target_biblio_record_entry($add_rec);
2997 $success = $U->simplereq('open-ils.actor',
2998 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2999 last unless $success;
3003 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3004 foreach my $add_rec (@$list) {
3005 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3006 $item->bucket($list_id);
3007 $item->target_biblio_record_entry($add_rec);
3008 $success = $U->simplereq('open-ils.actor',
3009 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3010 last unless $success;
3012 $self->clear_anon_cache;
3015 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3018 $self->ctx->{bucket_failure_noname} = 1;
3021 } elsif($action eq 'place_hold') {
3023 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3024 my $from_basket = scalar(@hold_recs);
3025 unless (@hold_recs) {
3026 if (@selected_item) {
3027 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3028 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3032 return Apache2::Const::OK unless @hold_recs;
3033 $logger->info("placing holds from list page on: @hold_recs");
3035 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3036 $url .= ';hold_target=' . $_ for @hold_recs;
3037 $url .= ';from_basket=1' if $from_basket;
3038 foreach my $param (('loc', 'qtype', 'query')) {
3039 if ($cgi->param($param)) {
3040 my @vals = $cgi->param($param);
3041 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3044 return $self->generic_redirect($url);
3046 } elsif ($action eq 'print') {
3047 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3048 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3049 if (!$incoming_sort) {
3050 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3052 if (!$incoming_sort) {
3053 $incoming_sort = 'author';
3056 $incoming_sort =~ s/sort.*$//;
3058 $self->ctx->{sort} = $incoming_sort;
3059 $self->ctx->{sort_dir} = $sort_dir;
3061 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3062 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3063 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3064 return $self->load_mylist_print($temp_cache_key);
3065 } elsif ($action eq 'email') {
3066 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3067 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3068 if (!$incoming_sort) {
3069 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3071 if (!$incoming_sort) {
3072 $incoming_sort = 'author';
3075 $incoming_sort =~ s/sort.*$//;
3077 $self->ctx->{sort} = $incoming_sort;
3078 $self->ctx->{sort_dir} = $sort_dir;
3080 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3081 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3082 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3083 return $self->load_mylist_email($temp_cache_key);
3086 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3088 return Apache2::Const::HTTP_BAD_REQUEST unless
3089 $list and $list->owner == $e->requestor->id;
3092 if($action eq 'delete') {
3093 $success = $U->simplereq('open-ils.actor',
3094 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3096 # We check to see if we're deleting the user's default list.
3097 $self->_load_user_with_prefs;
3098 my $settings_map = $self->ctx->{user_setting_map};
3099 if ($$settings_map{'opac.default_list'} == $list_id) {
3100 # We unset the user's opac.default_list setting.
3101 $success = $U->simplereq(
3103 'open-ils.actor.patron.settings.update',
3106 { 'opac.default_list' => 0 }
3110 } elsif($action eq 'show') {
3111 unless($U->is_true($list->pub)) {
3113 $success = $U->simplereq('open-ils.actor',
3114 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3117 } elsif($action eq 'hide') {
3118 if($U->is_true($list->pub)) {
3120 $success = $U->simplereq('open-ils.actor',
3121 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3124 } elsif($action eq 'rename') {
3127 $success = $U->simplereq('open-ils.actor',
3128 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3131 } elsif($action eq 'add_rec') {
3132 foreach my $add_rec (@add_rec) {
3133 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3134 $item->bucket($list_id);
3135 $item->target_biblio_record_entry($add_rec);
3136 $success = $U->simplereq('open-ils.actor',
3137 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3138 last unless $success;
3140 # Redirect back where we came from if we have an anchor parameter:
3141 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3142 $url = $self->ctx->{referer};
3143 $url =~ s/#.*|$/#$anchor/;
3144 } elsif ($cgi->param('where_from')) {
3145 # Or, if we have a "where_from" parameter.
3146 $url = $cgi->param('where_from');
3148 } elsif ($action eq 'del_item') {
3149 foreach (@selected_item) {
3150 $success = $U->simplereq(
3152 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3154 last unless $success;
3156 } elsif ($action eq 'save_notes') {
3157 $success = $self->update_bookbag_item_notes;
3158 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3159 } elsif ($action eq 'make_default') {
3160 $success = $U->simplereq(
3162 'open-ils.actor.patron.settings.update',
3165 { 'opac.default_list' => $list_id }
3167 } elsif ($action eq 'remove_default') {
3168 $success = $U->simplereq(
3170 'open-ils.actor.patron.settings.update',
3173 { 'opac.default_list' => 0 }
3177 return $self->generic_redirect($url) if $success;
3179 $self->ctx->{where_from} = $cgi->param('where_from');
3180 $self->ctx->{bucket_action} = $action;
3181 $self->ctx->{bucket_action_failed} = 1;
3182 return Apache2::Const::OK;
3185 sub update_bookbag_item_notes {
3187 my $e = $self->editor;
3189 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3190 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3192 # We're going to leverage an API call that's already been written to check
3193 # permissions appropriately.
3195 my $a = create OpenSRF::AppSession("open-ils.actor");
3196 my $method = "open-ils.actor.container.item_note.cud";
3198 for my $note_key (@note_keys) {
3201 my $id = ($note_key =~ /(\d+)/)[0];
3204 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3205 my $event = $e->die_event;
3206 $self->apache->log->warn(
3207 "error retrieving cbrebin id $id, got event " .
3211 $self->ctx->{bucket_action_event} = $event;
3215 if (length($self->cgi->param($note_key))) {
3216 $note->ischanged(1);
3217 $note->note($self->cgi->param($note_key));
3219 $note->isdeleted(1);
3222 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3224 if (defined $U->event_code($r)) {
3225 $self->apache->log->warn(
3226 "attempt to modify cbrebin " . $note->id .
3227 " returned event " . $r->{textcode}
3231 $self->ctx->{bucket_action_event} = $r;
3236 for my $item_key (@item_keys) {
3237 my $id = int(($item_key =~ /(\d+)/)[0]);
3238 my $text = $self->cgi->param($item_key);
3241 next unless length $text;
3243 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3248 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3250 if (defined $U->event_code($r)) {
3251 $self->apache->log->warn(
3252 "attempt to create cbrebin for item " . $note->item .
3253 " returned event " . $r->{textcode}
3257 $self->ctx->{bucket_action_event} = $r;
3266 sub load_myopac_bookbag_print {
3269 my $id = int($self->cgi->param("list"));
3271 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3274 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3278 # Get the bookbag object itself, assuming we're allowed to.
3279 if ($self->editor->allowed("VIEW_CONTAINER")) {
3281 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3283 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3287 "owner" => $self->editor->requestor->id,
3291 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3293 $bbag = pop @$bookbags;
3296 # If we have a bookbag we're allowed to look at, issue the A/T event
3297 # to get CSV, passing as a user param that search query we built before.
3299 $self->ctx->{csv} = $U->fire_object_event(
3300 undef, "container.biblio_record_entry_bucket.csv",
3301 $bbag, $self->editor->requestor->home_ou,
3302 undef, {"item_search" => $item_search}
3306 # Create a reasonable filename and set the content disposition to
3307 # provoke browser download dialogs.
3308 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3310 return $self->set_file_download_headers("$filename.csv");
3313 sub load_myopac_circ_history_export {
3315 my $e = $self->editor;
3316 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3318 my $circs = $self->fetch_user_circ_history(1);
3320 $self->ctx->{csv}->{circs} = $circs;
3321 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3325 sub load_myopac_reservations {
3327 my $e = $self->editor;
3328 my $ctx = $self->ctx;
3330 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3331 $e->authtoken, undef
3334 $ctx->{reservations} = $upcoming;
3335 return Apache2::Const::OK;
3339 sub load_password_reset {
3341 my $cgi = $self->cgi;
3342 my $ctx = $self->ctx;
3343 my $barcode = $cgi->param('barcode');
3344 my $username = $cgi->param('username');
3345 my $email = $cgi->param('email');
3346 my $pwd1 = $cgi->param('pwd1');
3347 my $pwd2 = $cgi->param('pwd2');
3348 my $uuid = $ctx->{page_args}->[0];
3352 $logger->info("patron password reset with uuid $uuid");
3354 if ($pwd1 and $pwd2) {
3356 if ($pwd1 eq $pwd2) {
3358 my $response = $U->simplereq(
3360 'open-ils.actor.patron.password_reset.commit',
3363 $logger->info("patron password reset response " . Dumper($response));
3365 if ($U->event_code($response)) { # non-success event
3367 my $code = $response->{textcode};
3369 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3370 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3373 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3374 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3379 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3382 } else { # passwords not equal
3384 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3387 } else { # 2 password values needed
3389 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3392 } elsif ($barcode or $username) {
3394 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3395 push(@params, $email) if $email;
3399 'open-ils.actor.patron.password_reset.request', @params);
3401 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3404 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3405 return Apache2::Const::OK;