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
1174 for my $id (@$hold_ids) {
1175 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1179 try { # if the service is not running, just let this fail silently
1180 $curbsides = $U->simplereq(
1181 'open-ils.curbside',
1182 'open-ils.curbside.fetch_mine.atomic',
1185 } catch Error with {};
1187 return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, curbsides => $curbsides };
1190 sub load_current_curbside_libs {
1192 my $ctx = $self->ctx;
1193 my $e = $self->editor;
1194 my $holds = $e->search_action_hold_request({
1195 usr => $e->requestor->id,
1196 shelf_time => { '!=' => undef },
1197 cancel_time => undef,
1198 fulfillment_time => undef
1202 for my $h (@$holds) {
1203 next if ($h->pickup_lib != $h->current_shelf_lib);
1204 $pickup_libs{$h->pickup_lib} = 1;
1207 my @curbside_pickup_libs;
1208 for my $pul (keys %pickup_libs) {
1209 push(@curbside_pickup_libs, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1212 $ctx->{curbside_pickup_libs} = [
1213 sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } @curbside_pickup_libs
1217 sub handle_hold_update {
1220 my $hold_ids = shift;
1221 my $e = $self->editor;
1222 my $ctx = $self->ctx;
1225 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1226 @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1228 my $circ = OpenSRF::AppSession->create('open-ils.circ');
1230 if($action =~ /cancel/) {
1232 for my $hold_id (@hold_ids) {
1233 my $resp = $circ->request(
1234 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1237 } elsif ($action =~ /activate|suspend/) {
1240 for my $hold_id (@hold_ids) {
1241 my $vals = {id => $hold_id};
1243 if($action =~ /activate/) {
1244 $vals->{frozen} = 'f';
1245 $vals->{thaw_date} = undef;
1247 } elsif($action =~ /suspend/) {
1248 $vals->{frozen} = 't';
1249 # $vals->{thaw_date} = TODO;
1251 push(@$vlist, $vals);
1254 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1255 $self->ctx->{hold_suspend_post_capture} = 1 if
1256 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1258 } elsif ($action eq 'edit') {
1261 my $val = {"id" => $_};
1262 $val->{"frozen"} = $self->cgi->param("frozen");
1263 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1264 $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1265 $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1266 $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1267 $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1269 for my $field (qw/expire_time thaw_date/) {
1270 # XXX TODO make this support other date formats, not just
1272 next unless $self->cgi->param($field) =~
1273 m:^(\d{2})/(\d{2})/(\d{4})$:;
1274 $val->{$field} = "$3-$1-$2";
1277 $val->{holdable_formats} = # no-op for non-MR holds
1278 $self->compile_holdable_formats(undef, $_);
1284 'open-ils.circ.hold.update.batch.atomic',
1285 $e->authtoken, undef, \@vals
1286 )->gather(1); # LFW XXX test for failure
1287 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1288 foreach my $param (('loc', 'qtype', 'query')) {
1289 if ($self->cgi->param($param)) {
1290 my @vals = $self->cgi->param($param);
1291 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1294 } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1297 $circ = OpenSRF::AppSession->create('open-ils.curbside');
1299 # see what we're doing with curbside here...
1300 my $cs_action = $self->cgi->param("cs_action");
1301 my $slot_id = $self->cgi->param("cs_slot_id");
1303 # we have an id, let's grab it if we can
1304 my $slot = $e->retrieve_action_curbside($slot_id);
1305 $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1307 my $org = $self->cgi->param("cs_org");
1308 my $date = $self->cgi->param("cs_date");
1309 my $time = $self->cgi->param("cs_time");
1310 my $notes = $self->cgi->param("cs_notes");
1313 $org ||= $slot->org;
1314 $notes ||= $slot->notes;
1316 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1317 $date ||= $dt->strftime('%F');
1318 $time ||= $dt->strftime('%T');
1322 $ctx->{cs_org} = $org;
1323 $ctx->{cs_date} = $date;
1324 $ctx->{cs_time} = $time;
1325 $ctx->{cs_notes} = $notes;
1326 $ctx->{cs_slot_id} = $slot->id if ($slot);
1327 $ctx->{cs_slot} = $slot;
1329 if ($cs_action eq 'reset') {
1330 $ctx->{cs_org} = $org = undef;
1331 $ctx->{cs_date} = $date = undef;
1332 $ctx->{cs_time} = $time = undef;
1333 $ctx->{cs_notes} = $notes = undef;
1334 $ctx->{cs_slot_id} = $slot_id = undef;
1335 $ctx->{cs_slot} = $slot = undef;
1336 } elsif ($cs_action eq 'save' && $org && $date && $time) {
1337 my $mode = $slot ? 'update' : 'create';
1338 $slot = $circ->request(
1339 "open-ils.curbside.${mode}_appointment",
1340 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1343 if (defined $U->event_code($slot)) {
1344 $self->apache->log->warn(
1345 "error attempting to $mode a curbside appointment for patron ".
1346 $e->requestor->id . ", got event " . $slot->{textcode}
1348 $ctx->{curbside_action_event} = $slot;
1349 $ctx->{cs_slot} = undef;
1351 $ctx->{cs_slot} = $slot;
1353 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1354 } elsif ($cs_action eq 'cancel' && $slot) {
1355 my $curbsides = $U->simplereq(
1356 'open-ils.curbside',
1357 'open-ils.curbside.delete_appointment',
1358 $e->authtoken, $slot->id
1360 $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1361 } elsif ($cs_action eq 'arrive' && $slot) {
1362 my $curbsides = $U->simplereq(
1363 'open-ils.curbside',
1364 'open-ils.curbside.mark_arrived',
1365 $e->authtoken, $slot->id
1367 } elsif ($cs_action eq 'deliver' && $slot) {
1368 my $curbsides = $U->simplereq(
1369 'open-ils.curbside',
1370 'open-ils.curbside.mark_delivered',
1371 $e->authtoken, $slot->id
1375 if ($date and $org and !$ctx->{cs_times}{$org}{$date}) {
1376 $ctx->{cs_times}{$org}{$date} = $circ->request(
1377 'open-ils.curbside.times_for_date.atomic',
1378 $e->authtoken, $date, $org
1384 return defined($url) ? $self->generic_redirect($url) : undef;
1387 sub load_myopac_holds {
1389 my $e = $self->editor;
1390 my $ctx = $self->ctx;
1392 my $limit = $self->cgi->param('limit') || 15;
1393 my $offset = $self->cgi->param('offset') || 0;
1394 my $action = $self->cgi->param('action') || '';
1395 my $hold_id = $self->cgi->param('hid');
1396 my $available = int($self->cgi->param('available') || 0);
1398 my $hold_handle_result;
1399 $hold_handle_result = $self->handle_hold_update($action) if $action;
1402 if ($self->cgi->param('sort') ne "") {
1403 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1406 $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1409 if($holds_object->{holds}) {
1410 $ctx->{holds} = $holds_object->{holds};
1411 $ctx->{curbside_appointments} = {};
1413 $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1415 for my $cs (@{$holds_object->{curbsides}}) {
1417 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1418 $ctx->{cs_times}{$cs->org}{$dt} = $U->simplereq(
1419 'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1420 $e->authtoken, $dt, $cs->org
1423 $ctx->{curbside_appointments}{$cs->org} = $cs;
1426 $ctx->{holds_ids} = $holds_object->{all_ids};
1427 $ctx->{holds_limit} = $limit;
1428 $ctx->{holds_offset} = $offset;
1430 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1435 sub load_place_hold {
1437 my $ctx = $self->ctx;
1438 my $gos = $ctx->{get_org_setting};
1439 my $e = $self->editor;
1440 my $cgi = $self->cgi;
1442 $self->ctx->{page} = 'place_hold';
1443 my @targets = uniq $cgi->param('hold_target');
1444 my @parts = $cgi->param('part');
1446 $ctx->{hold_type} = $cgi->param('hold_type');
1447 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1448 $ctx->{email_notify} = $cgi->param('email_notify');
1449 if ($cgi->param('phone_notify_checkbox')) {
1450 $ctx->{phone_notify} = $cgi->param('phone_notify');
1452 if ($cgi->param('sms_notify_checkbox')) {
1453 $ctx->{sms_notify} = $cgi->param('sms_notify');
1454 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1457 return $self->generic_redirect unless @targets;
1459 # Check for multiple hold placement via the num_copies widget.
1460 my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1461 if ($num_copies > 1) {
1462 # Only if we have 1 hold target and no parts.
1463 if (scalar(@targets) == 1 && !$parts[0]) {
1464 # Also, only for M and T holds.
1465 if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1466 # Add the extra holds to @targets. NOTE: We start with
1467 # 1 and go to < $num_copies to account for the
1469 for (my $i = 1; $i < $num_copies; $i++) {
1470 push(@targets, $targets[0]);
1476 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1478 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1483 au => ['settings', 'card']
1486 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1487 my $user_setting_map = {
1488 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1490 $ctx->{staff_recipient}->settings
1493 $ctx->{user_setting_map} = $user_setting_map;
1495 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1496 if ($default_notify =~ /email/) {
1497 $ctx->{default_email_notify} = 'checked';
1499 $ctx->{default_email_notify} = '';
1501 if ($default_notify =~ /phone/) {
1502 $ctx->{default_phone_notify} = 'checked';
1504 $ctx->{default_phone_notify} = '';
1506 if ($default_notify =~ /sms/) {
1507 $ctx->{default_sms_notify} = 'checked';
1509 $ctx->{default_sms_notify} = '';
1511 if ($cgi->param('hold_suspend')) {
1513 # TODO: Make this support other date formats, not just mm/dd/yyyy.
1514 # We should use a date input type on the forms once it is supported by Firefox.
1515 # I didn't do that now because it is not available in a general release.
1516 if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1518 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1519 $ctx->{thaw_date} = $dt->ymd;
1522 $logger->warn("ignoring invalid thaw_date when placing hold request");
1528 # If we have a default pickup location, grab it
1529 if ($$user_setting_map{'opac.default_pickup_location'}) {
1530 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1533 my $request_lib = $e->requestor->ws_ou;
1535 $ctx->{hold_data} = \@hold_data;
1537 $data_filler = sub {
1539 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1540 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1541 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1542 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1543 if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1544 if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1548 my $type_dispatch = {
1550 # target metarecords
1551 my $mrecs = $e->batch_retrieve_metabib_metarecord([
1553 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1557 for my $id (@targets) {
1558 my ($mr) = grep {$_->id eq $id} @$mrecs;
1560 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1561 my $filter_data = $U->simplereq(
1563 'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1565 my $holdable_formats =
1566 $self->compile_holdable_formats($mr->id);
1568 push(@hold_data, $data_filler->({
1570 record => $mr->master_record,
1571 holdable_formats => $holdable_formats,
1572 metarecord_filters => $filter_data->{metarecord}
1577 my $recs = $e->batch_retrieve_biblio_record_entry(
1578 [\@targets, {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1582 for my $id (@targets) { # force back into the correct order
1583 my ($rec) = grep {$_->id eq $id} @$recs;
1585 # NOTE: if tpac ever supports locked-down pickup libs,
1586 # we'll need to pass a pickup_lib param along with the
1587 # record to filter the set of monographic parts.
1588 my $parts = $U->simplereq(
1590 'open-ils.search.biblio.record_hold_parts',
1591 {record => $rec->id}
1594 # T holds on records that have parts are OK, but if the record has
1595 # no non-part copies, the hold will ultimately fail. When that
1596 # happens, require the user to select a part.
1597 my $part_required = 0;
1599 my $np_copies = $e->json_query({
1600 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1601 from => {acp => {acn => {}, acpm => {type => 'left'}}},
1603 '+acp' => {deleted => 'f'},
1604 '+acn' => {deleted => 'f', record => $rec->id},
1605 '+acpm' => {id => undef}
1608 $part_required = 1 if $np_copies->[0]->{count} == 0;
1611 push(@hold_data, $data_filler->({
1615 part_required => $part_required
1620 my $vols = $e->batch_retrieve_asset_call_number([
1623 "flesh_fields" => {"acn" => ["record"]}
1625 ], {substream => 1});
1627 for my $id (@targets) {
1628 my ($vol) = grep {$_->id eq $id} @$vols;
1629 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1633 my $copies = $e->batch_retrieve_asset_copy([
1637 "acn" => ["record"],
1638 "acp" => ["call_number"]
1641 ], {substream => 1});
1643 for my $id (@targets) {
1644 my ($copy) = grep {$_->id eq $id} @$copies;
1645 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1649 my $isses = $e->batch_retrieve_serial_issuance([
1653 "siss" => ["subscription"], "ssub" => ["record_entry"]
1656 ], {substream => 1});
1658 for my $id (@targets) {
1659 my ($iss) = grep {$_->id eq $id} @$isses;
1660 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1665 }->{$ctx->{hold_type}}->();
1667 # caller sent bad target IDs or the wrong hold type
1668 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1670 # generate the MARC xml for each record
1671 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1673 my $pickup_lib = $cgi->param('pickup_lib');
1674 # no pickup lib means no holds placement
1675 return Apache2::Const::OK unless $pickup_lib;
1677 $ctx->{hold_attempt_made} = 1;
1679 # Give the original CGI params back to the user in case they
1680 # want to try to override something.
1681 $ctx->{orig_params} = $cgi->Vars;
1682 delete $ctx->{orig_params}{submit};
1683 delete $ctx->{orig_params}{hold_target};
1684 delete $ctx->{orig_params}{part};
1686 my $usr = $e->requestor->id;
1688 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1689 # find the real hold target
1691 $usr = $U->simplereq(
1693 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1694 $e->authtoken, $cgi->param("hold_usr"));
1696 if (defined $U->event_code($usr)) {
1697 $ctx->{hold_failed} = 1;
1698 $ctx->{hold_failed_event} = $usr;
1702 # target_id is the true target_id for holds placement.
1703 # needed for attempt_hold_placement()
1704 # With the exception of P-type holds, target_id == target->id.
1705 $_->{target_id} = $_->{target}->id for @hold_data;
1707 if ($ctx->{hold_type} eq 'T') {
1709 # Much like quantum wave-particles, P-type holds pop into
1710 # and out of existence at the user's whim. For our purposes,
1711 # we treat such holds as T(itle) holds with a selected_part
1712 # designation. When the time comes to pass the hold information
1713 # off for holds possibility testing and placement, make it look
1714 # like a real P-type hold.
1715 my (@p_holds, @t_holds);
1717 # Now that we have the num_copies field for mutliple title and
1718 # metarecord hold placement, the number of holds and parts
1719 # arrays can get out of sync. We only want to parse out parts
1720 # if the numbers are equal.
1721 if ($#hold_data == $#parts) {
1722 for my $idx (0..$#parts) {
1723 my $hdata = $hold_data[$idx];
1724 if (my $part = $parts[$idx]) {
1725 $hdata->{target_id} = $part;
1726 $hdata->{selected_part} = $part;
1727 push(@p_holds, $hdata);
1729 push(@t_holds, $hdata);
1733 @t_holds = @hold_data;
1736 $self->apache->log->warn("$#parts : @t_holds");
1738 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1739 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1742 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1745 # NOTE: we are leaving the staff-placed patron barcode cookie
1746 # in place. Otherwise, it's not possible to place more than
1747 # one hold for the patron within a staff/patron session. This
1748 # does leave the barcode to linger longer than is ideal, but
1749 # normal staff work flow will cause the cookie to be replaced
1750 # with each new patron anyway.
1751 # TODO: See about getting the staff client to clear the cookie
1753 # return to the place_hold page so the results of the hold
1754 # placement attempt can be reported to the user
1755 return Apache2::Const::OK;
1758 sub attempt_hold_placement {
1759 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1760 my $cgi = $self->cgi;
1761 my $ctx = $self->ctx;
1762 my $e = $self->editor;
1764 # First see if we should warn/block for any holds that
1765 # might have locally available items.
1766 for my $hdata (@hold_data) {
1767 my ($local_block, $local_alert) = $self->local_avail_concern(
1768 $hdata->{target_id}, $hold_type, $pickup_lib);
1771 $hdata->{hold_failed} = 1;
1772 $hdata->{hold_local_block} = 1;
1773 } elsif ($local_alert) {
1774 $hdata->{hold_failed} = 1;
1775 $hdata->{hold_local_alert} = 1;
1779 my $method = 'open-ils.circ.holds.test_and_create.batch';
1781 if ($cgi->param('override')) {
1782 $method .= '.override';
1784 } elsif (!$ctx->{is_staff}) {
1786 $method .= '.override' if $self->ctx->{get_org_setting}->(
1787 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1790 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1793 if(@create_targets) {
1795 # holdable formats may be different for each MR hold.
1796 # map each set to the ID of the target.
1797 my $holdable_formats = {};
1798 if ($hold_type eq 'M') {
1799 $holdable_formats->{$_->{target_id}} =
1800 $_->{holdable_formats} for @hold_data;
1803 my $bses = OpenSRF::AppSession->create('open-ils.circ');
1804 my $breq = $bses->request(
1809 pickup_lib => $pickup_lib,
1810 hold_type => $hold_type,
1811 holdable_formats_map => $holdable_formats,
1816 while (my $resp = $breq->recv) {
1818 $resp = $resp->content;
1819 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1821 if ($U->event_code($resp)) {
1822 $ctx->{general_hold_error} = $resp;
1826 # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1827 my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1828 my $result = $resp->{result};
1830 if ($U->event_code($result)) {
1831 # e.g. permission denied
1832 $hdata->{hold_failed} = 1;
1833 $hdata->{hold_failed_event} = $result;
1837 if(not ref $result and $result > 0) {
1838 # successul hold returns the hold ID
1840 $hdata->{hold_success} = $result;
1843 # hold-specific failure event
1844 $hdata->{hold_failed} = 1;
1846 if (ref $result eq 'HASH') {
1847 $hdata->{hold_failed_event} = $result->{last_event};
1849 if ($result->{age_protected_copy}) {
1850 my %temp = %{$hdata->{hold_failed_event}};
1851 my $theTextcode = $temp{"textcode"};
1852 $theTextcode.=".override";
1853 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1854 $hdata->{age_protect} = 1;
1856 $hdata->{could_override} = $result->{place_unfillable} ||
1857 $self->test_could_override($hdata->{hold_failed_event});
1859 } elsif (ref $result eq 'ARRAY') {
1860 $hdata->{hold_failed_event} = $result->[0];
1862 if ($result->[3]) { # age_protect_only
1863 my %temp = %{$hdata->{hold_failed_event}};
1864 my $theTextcode = $temp{"textcode"};
1865 $theTextcode.=".override";
1866 $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1867 $hdata->{age_protect} = 1;
1869 $hdata->{could_override} = $result->[4] || # place_unfillable
1870 $self->test_could_override($hdata->{hold_failed_event});
1880 if ($self->cgi->param('clear_cart')) {
1881 $self->clear_anon_cache;
1885 # pull the selected formats and languages for metarecord holds
1886 # from the CGI params and map them into the JSON holdable
1887 # formats...er, format.
1888 # if no metarecord is provided, we'll pull it from the target
1889 # of the provided hold.
1890 sub compile_holdable_formats {
1891 my ($self, $mr_id, $hold_id) = @_;
1892 my $e = $self->editor;
1893 my $cgi = $self->cgi;
1895 # exit early if not needed
1897 grep /metarecord_formats_|metarecord_langs_/,
1900 # CGI params are based on the MR id, since during hold placement
1901 # we have no old ID. During hold edit, map the hold ID back to
1902 # the metarecod target.
1904 $e->retrieve_action_hold_request($hold_id)->target
1907 my $format_attr = $self->ctx->{get_cgf}->(
1908 'opac.metarecord.holds.format_attr');
1910 if (!$format_attr) {
1911 $logger->error("Missing config.global_flag: ".
1912 "opac.metarecord.holds.format_attr!");
1916 $format_attr = $format_attr->value;
1918 # during hold placement or edit submission, the user selects
1919 # which of the available formats/langs are acceptable.
1920 # Capture those here as the holdable_formats for the MR hold.
1921 my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1922 my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1924 # map the selected attrs into the JSON holdable_formats structure
1926 if (@selected_formats) {
1928 map { {_attr => $format_attr, _val => $_} }
1932 if (@selected_langs) {
1934 map { {_attr => 'item_lang', _val => $_} }
1939 return OpenSRF::Utils::JSON->perl2JSON($blob);
1942 sub fetch_user_circs {
1944 my $flesh = shift; # flesh bib data, etc.
1945 my $circ_ids = shift;
1949 my $e = $self->editor;
1954 @circ_ids = @$circ_ids;
1959 select => {circ => ['id']},
1963 usr => $e->requestor->id,
1964 checkin_time => undef,
1966 {stop_fines => undef},
1967 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1971 order_by => {circ => ['due_date']}
1974 $query->{limit} = $limit if $limit;
1975 $query->{offset} = $offset if $offset;
1977 my $ids = $e->json_query($query);
1978 @circ_ids = map {$_->{id}} @$ids;
1981 return [] unless @circ_ids;
1986 circ => ['target_copy'],
1987 acp => ['call_number'],
1988 acn => ['record','owning_lib']
1993 my $circs = $e->search_action_circulation(
1994 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1997 for my $circ (@$circs) {
2000 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2001 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2002 undef # pre-cat copy, use the dummy title/author instead
2007 # make sure the final list is in the correct order
2009 for my $id (@circ_ids) {
2012 (grep { $_->{circ}->id == $id } @circs)
2016 return \@sorted_circs;
2020 sub handle_circ_renew {
2023 my $ctx = $self->ctx;
2025 my @renew_ids = $self->cgi->param('circ');
2027 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2029 # TODO: fire off renewal calls in batches to speed things up
2031 for my $circ (@$circs) {
2033 my $evt = $U->simplereq(
2035 'open-ils.circ.renew',
2036 $self->editor->authtoken,
2038 patron_id => $self->editor->requestor->id,
2039 copy_id => $circ->{circ}->target_copy,
2044 # TODO return these, then insert them into the circ data
2045 # blob that is shoved into the template for each circ
2046 # so the template won't have to match them
2047 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2053 sub load_myopac_circs {
2055 my $e = $self->editor;
2056 my $ctx = $self->ctx;
2059 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2060 my $offset = $self->cgi->param('offset') || 0;
2061 my $action = $self->cgi->param('action') || '';
2063 # perform the renewal first if necessary
2064 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2066 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2068 my $success_renewals = 0;
2069 my $failed_renewals = 0;
2070 for my $data (@{$ctx->{circs}}) {
2071 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2074 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2076 # extract the fail_part, if present, from the event payload;
2077 # since # the payload is an acp object in some cases,
2078 # blindly looking for a # 'fail_part' key in the template can
2080 $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2081 $evt->{payload}->{fail_part} :
2084 $data->{renewal_response} = $evt;
2085 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2086 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2090 $ctx->{success_renewals} = $success_renewals;
2091 $ctx->{failed_renewals} = $failed_renewals;
2093 return Apache2::Const::OK;
2096 sub load_myopac_circ_history {
2098 my $e = $self->editor;
2099 my $ctx = $self->ctx;
2100 my $limit = $self->cgi->param('limit') || 15;
2101 my $offset = $self->cgi->param('offset') || 0;
2102 my $action = $self->cgi->param('action') || '';
2104 my $circ_handle_result;
2105 $circ_handle_result = $self->handle_circ_update($action) if $action;
2107 $ctx->{circ_history_limit} = $limit;
2108 $ctx->{circ_history_offset} = $offset;
2110 # Defer limitation to circ_history.tt2 when sorting
2111 if ($self->cgi->param('sort')) {
2116 $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2117 return Apache2::Const::OK;
2120 # if 'flesh' is set, copy data etc. is loaded and the return value is
2121 # a hash of 'circ' and 'marc_xml'. Othwerwise, it's just a list of
2123 sub fetch_user_circ_history {
2124 my ($self, $flesh, $limit, $offset) = @_;
2125 my $e = $self->editor;
2128 $limits{offset} = $offset if defined $offset;
2129 $limits{limit} = $limit if defined $limit;
2134 auch => ['target_copy','source_circ'],
2135 acp => ['call_number'],
2141 my $circs = $e->search_action_user_circ_history(
2143 {usr => $e->requestor->id},
2144 { # order newest to oldest by default
2145 order_by => {auch => 'xact_start DESC'},
2146 $flesh ? %flesh_ops : (),
2154 return $circs unless $flesh;
2158 my %unapi_cache = ();
2159 for my $circ (@$circs) {
2160 if ($circ->target_copy->call_number->id == -1) {
2163 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2167 my $bre_id = $circ->target_copy->call_number->record->id;
2169 if (exists $unapi_cache{$bre_id}) {
2170 $unapi = $unapi_cache{$bre_id};
2172 my $result = $e->json_query({
2174 'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2178 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2189 marc_xml => undef # failed, but try to go on
2198 sub handle_circ_update {
2201 my $circ_ids = shift;
2203 $circ_ids //= [$self->cgi->param('circ_id')];
2205 if ($action =~ /delete/) {
2207 circ_ids => $circ_ids,
2212 'open-ils.actor.history.circ.clear',
2213 $self->editor->authtoken,
2221 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
2222 sub load_myopac_hold_history {
2224 my $e = $self->editor;
2225 my $ctx = $self->ctx;
2226 my $limit = $self->cgi->param('limit') || 15;
2227 my $offset = $self->cgi->param('offset') || 0;
2228 $ctx->{hold_history_limit} = $limit;
2229 $ctx->{hold_history_offset} = $offset;
2231 my $hold_ids = $e->json_query({
2235 transform => 'action.usr_visible_holds',
2236 result_field => 'id'
2240 where => {id => $e->requestor->id}
2243 my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2244 if($holds_object->{holds}) {
2245 $ctx->{holds} = $holds_object->{holds};
2247 $ctx->{hold_history_ids} = $holds_object->{all_ids};
2249 return Apache2::Const::OK;
2252 sub load_myopac_payment_form {
2256 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
2257 $r = $self->prepare_extended_user_info and return $r;
2259 return Apache2::Const::OK;
2262 # TODO: add other filter options as params/configs/etc.
2263 sub load_myopac_payments {
2265 my $limit = $self->cgi->param('limit') || 20;
2266 my $offset = $self->cgi->param('offset') || 0;
2267 my $e = $self->editor;
2269 $self->ctx->{payment_history_limit} = $limit;
2270 $self->ctx->{payment_history_offset} = $offset;
2273 $args->{limit} = $limit if $limit;
2274 $args->{offset} = $offset if $offset;
2276 if (my $max_age = $self->ctx->{get_org_setting}->(
2277 $e->requestor->home_ou, "opac.payment_history_age_limit"
2279 my $min_ts = DateTime->now(
2280 "time_zone" => DateTime::TimeZone->new("name" => "local"),
2281 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2283 $logger->info("XXX min_ts: $min_ts");
2284 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2287 $self->ctx->{payments} = $U->simplereq(
2289 'open-ils.actor.user.payments.retrieve.atomic',
2290 $e->authtoken, $e->requestor->id, $args);
2292 return Apache2::Const::OK;
2295 # 1. caches the form parameters
2296 # 2. loads the credit card payment "Processing..." page
2297 sub load_myopac_pay_init {
2299 my $cache = OpenSRF::Utils::Cache->new('global');
2301 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2303 if (!@payment_xacts) {
2304 # for consistency with load_myopac_payment_form() and
2305 # to preserve backwards compatibility, if no xacts are
2306 # selected, assume all (applicable) transactions are wanted.
2307 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2308 return $stat if $stat;
2310 map { $_->{xact}->id } (
2311 @{$self->ctx->{fines}->{circulation}},
2312 @{$self->ctx->{fines}->{grocery}}
2316 return $self->generic_redirect unless @payment_xacts;
2318 my $cc_args = {"where_process" => 1};
2320 $cc_args->{$_} = $self->cgi->param($_) for (qw/
2321 number cvv2 expire_year expire_month billing_first
2322 billing_last billing_address billing_city billing_state
2323 billing_zip stripe_token
2327 cc_args => $cc_args,
2328 user => $self->ctx->{user}->id,
2329 xacts => \@payment_xacts
2332 # generate a temporary cache token and cache the form data
2333 my $token = md5_hex($$ . time() . rand());
2334 $cache->put_cache($token, $cache_args, 30);
2336 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2338 # after we render the processing page, we quickly redirect to submit
2339 # the actual payment. The refresh url contains the payment token.
2340 # It also contains the list of xact IDs, which allows us to clear the
2341 # cache at the earliest possible time while leaving a trace of which
2342 # transactions we were processing, so the UI can bring the user back
2343 # to the payment form w/ the same xacts if the payment fails.
2345 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2346 $refresh .= ";xact=$_" for @payment_xacts;
2347 $self->ctx->{refresh} = $refresh;
2349 return Apache2::Const::OK;
2352 # retrieve the cached CC payment info and send off for processing
2353 sub load_myopac_pay {
2355 my $token = $self->ctx->{page_args}->[0];
2356 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2358 my $cache = OpenSRF::Utils::Cache->new('global');
2359 my $cache_args = $cache->get_cache($token);
2360 $cache->delete_cache($token);
2362 # this page is loaded immediately after the token is created.
2363 # if the cached data is not there, it's because of an invalid
2364 # token (or cache failure) and not because of a timeout.
2365 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2367 my @payment_xacts = @{$cache_args->{xacts}};
2368 my $cc_args = $cache_args->{cc_args};
2370 # as an added security check, verify the user submitting
2371 # the form is the same as the user whose data was cached
2372 return Apache2::Const::HTTP_BAD_REQUEST unless
2373 $cache_args->{user} == $self->ctx->{user}->id;
2375 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2378 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2380 # balance_owed is computed specifically from the fines we're paying
2381 if ($self->ctx->{fines}->{balance_owed} <= 0) {
2382 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2383 return Apache2::Const::HTTP_BAD_REQUEST;
2387 "cc_args" => $cc_args,
2388 "userid" => $self->ctx->{user}->id,
2389 "payment_type" => "credit_card_payment",
2390 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
2393 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2394 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2397 $self->ctx->{"payment_response"} = $resp;
2399 unless ($resp->{"textcode"}) {
2400 $self->ctx->{printable_receipt} = $U->simplereq(
2401 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2402 $self->editor->authtoken, $resp->{payments}
2406 return Apache2::Const::OK;
2409 sub load_myopac_receipt_print {
2412 $self->ctx->{printable_receipt} = $U->simplereq(
2413 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2414 $self->editor->authtoken, [$self->cgi->param("payment")]
2417 return Apache2::Const::OK;
2420 sub load_myopac_receipt_email {
2423 # The following ML method doesn't actually check whether the user in
2424 # question has an email address, so we do.
2425 if ($self->ctx->{user}->email) {
2426 $self->ctx->{email_receipt_result} = $U->simplereq(
2427 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2428 $self->editor->authtoken, [$self->cgi->param("payment")]
2431 $self->ctx->{email_receipt_result} =
2432 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2435 return Apache2::Const::OK;
2439 my ($self, $limit, $offset, $id_list) = @_;
2441 # XXX TODO: check for failure after various network calls
2443 # It may be unclear, but this result structure lumps circulation and
2444 # reservation fines together, and keeps grocery fines separate.
2445 $self->ctx->{"fines"} = {
2446 "circulation" => [],
2453 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2455 # TODO: This should really be a ML call, but the existing calls
2456 # return an excessive amount of data and don't offer streaming
2458 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2460 my $req = $cstore->request(
2461 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2463 usr => $self->editor->requestor->id,
2464 balance_owed => {'!=' => 0},
2465 ($id_list && @$id_list ? ("id" => $id_list) : ()),
2470 mobts => [qw/grocery circulation reservation/],
2471 bresv => ['target_resource_type'],
2475 circ => ['target_copy'],
2476 acp => ['call_number'],
2479 order_by => { mobts => 'xact_start' },
2484 # Collect $$ amounts from each transaction for summing below.
2485 my (@paid_amounts, @owed_amounts, @balance_amounts);
2487 while(my $resp = $req->recv) {
2488 my $mobts = $resp->content;
2489 my $circ = $mobts->circulation;
2492 if($mobts->grocery) {
2493 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2494 $last_billing = pop(@billings);
2497 push(@paid_amounts, $mobts->total_paid);
2498 push(@owed_amounts, $mobts->total_owed);
2499 push(@balance_amounts, $mobts->balance_owed);
2501 my $marc_xml = undef;
2502 if ($mobts->xact_type eq 'reservation' and
2503 $mobts->reservation->target_resource_type->record) {
2504 $marc_xml = XML::LibXML->new->parse_string(
2505 $mobts->reservation->target_resource_type->record->marc
2507 } elsif ($mobts->xact_type eq 'circulation' and
2508 $circ->target_copy->call_number->id != -1) {
2509 $marc_xml = XML::LibXML->new->parse_string(
2510 $circ->target_copy->call_number->record->marc
2515 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2518 last_grocery_billing => $last_billing,
2519 marc_xml => $marc_xml
2526 $self->ctx->{"fines"}->{total_paid} = $U->fpsum(@paid_amounts);
2527 $self->ctx->{"fines"}->{total_owed} = $U->fpsum(@owed_amounts);
2528 $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2533 sub prepare_fines_for_payment {
2534 # This assumes $self->prepare_fines has already been run
2538 if ($self->ctx->{fines}) {
2539 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2540 @{$self->ctx->{fines}->{circulation}},
2541 @{$self->ctx->{fines}->{grocery}}
2548 sub load_myopac_main {
2550 my $limit = $self->cgi->param('limit') || 0;
2551 my $offset = $self->cgi->param('offset') || 0;
2552 $self->ctx->{search_ou} = $self->_get_search_lib();
2553 $self->ctx->{user}->notes(
2554 $self->editor->search_actor_usr_note({
2555 usr => $self->ctx->{user}->id,
2559 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2562 sub load_myopac_update_email {
2564 my $e = $self->editor;
2565 my $ctx = $self->ctx;
2566 my $email = $self->cgi->param('email') || '';
2567 my $current_pw = $self->cgi->param('current_pw') || '';
2569 # needed for most up-to-date email address
2570 if (my $r = $self->prepare_extended_user_info) { return $r };
2572 return Apache2::Const::OK
2573 unless $self->cgi->request_method eq 'POST';
2575 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2576 $ctx->{invalid_email} = $email;
2577 return Apache2::Const::OK;
2580 my $stat = $U->simplereq(
2582 'open-ils.actor.user.email.update',
2583 $e->authtoken, $email, $current_pw);
2585 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2586 $ctx->{password_incorrect} = 1;
2587 return Apache2::Const::OK;
2590 unless ($self->cgi->param("redirect_to")) {
2591 my $url = $self->apache->unparsed_uri;
2592 $url =~ s/update_email/prefs/;
2594 return $self->generic_redirect($url);
2597 return $self->generic_redirect;
2600 sub load_myopac_update_username {
2602 my $e = $self->editor;
2603 my $ctx = $self->ctx;
2604 my $username = $self->cgi->param('username') || '';
2605 my $current_pw = $self->cgi->param('current_pw') || '';
2607 $self->prepare_extended_user_info;
2609 my $allow_change = 1;
2611 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2612 if(defined($lock_usernames) and $lock_usernames == 1) {
2613 # Policy says no username changes
2616 # We want this further down.
2617 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2618 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2619 if(!$username_unlimit) {
2621 # Default is "starts with a number"
2622 $regex_check = '^\d+';
2624 # You already have a username?
2625 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2630 if(!$allow_change) {
2631 my $url = $self->apache->unparsed_uri;
2632 $url =~ s/update_username/prefs/;
2634 return $self->generic_redirect($url);
2637 return Apache2::Const::OK
2638 unless $self->cgi->request_method eq 'POST';
2640 unless($username and $username !~ /\s/) { # any other username restrictions?
2641 $ctx->{invalid_username} = $username;
2642 return Apache2::Const::OK;
2645 # New username can't look like a barcode if we have a barcode regex
2646 if($regex_check and $username =~ /$regex_check/) {
2647 $ctx->{invalid_username} = $username;
2648 return Apache2::Const::OK;
2651 # New username has to look like a username if we have a username regex
2652 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2653 if($regex_check and $username !~ /$regex_check/) {
2654 $ctx->{invalid_username} = $username;
2655 return Apache2::Const::OK;
2658 if($username ne $e->requestor->usrname) {
2660 my $evt = $U->simplereq(
2662 'open-ils.actor.user.username.update',
2663 $e->authtoken, $username, $current_pw);
2665 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2666 $ctx->{password_incorrect} = 1;
2667 return Apache2::Const::OK;
2670 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2671 $ctx->{username_exists} = $username;
2672 return Apache2::Const::OK;
2676 my $url = $self->apache->unparsed_uri;
2677 $url =~ s/update_username/prefs/;
2679 return $self->generic_redirect($url);
2682 sub load_myopac_update_password {
2684 my $e = $self->editor;
2685 my $ctx = $self->ctx;
2687 return Apache2::Const::OK
2688 unless $self->cgi->request_method eq 'POST';
2690 my $current_pw = $self->cgi->param('current_pw') || '';
2691 my $new_pw = $self->cgi->param('new_pw') || '';
2692 my $new_pw2 = $self->cgi->param('new_pw2') || '';
2694 unless($new_pw eq $new_pw2) {
2695 $ctx->{password_nomatch} = 1;
2696 return Apache2::Const::OK;
2699 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2702 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2703 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2706 if($pw_regex and $new_pw !~ /$pw_regex/) {
2707 $ctx->{password_invalid} = 1;
2708 return Apache2::Const::OK;
2711 my $evt = $U->simplereq(
2713 'open-ils.actor.user.password.update',
2714 $e->authtoken, $new_pw, $current_pw);
2717 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2718 $ctx->{password_incorrect} = 1;
2719 return Apache2::Const::OK;
2722 my $url = $self->apache->unparsed_uri;
2723 $url =~ s/update_password/prefs/;
2725 return $self->generic_redirect($url);
2728 sub _update_bookbag_metadata {
2729 my ($self, $bookbag) = @_;
2731 $bookbag->name($self->cgi->param("name"));
2732 $bookbag->description($self->cgi->param("description"));
2734 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2738 sub _get_lists_per_page {
2741 if($self->editor->requestor) {
2742 $self->timelog("Checking for opac.lists_per_page preference");
2743 # See if the user has a lists per page preference
2744 my $ipp = $self->editor->search_actor_user_setting({
2745 usr => $self->editor->requestor->id,
2746 name => 'opac.lists_per_page'
2748 $self->timelog("Got opac.lists_per_page preference");
2749 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2751 return 10; # default
2754 sub _get_items_per_page {
2757 if($self->editor->requestor) {
2758 $self->timelog("Checking for opac.list_items_per_page preference");
2759 # See if the user has a list items per page preference
2760 my $ipp = $self->editor->search_actor_user_setting({
2761 usr => $self->editor->requestor->id,
2762 name => 'opac.list_items_per_page'
2764 $self->timelog("Got opac.list_items_per_page preference");
2765 return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2767 return 10; # default
2770 sub load_myopac_bookbags {
2772 my $e = $self->editor;
2773 my $ctx = $self->ctx;
2774 my $limit = $self->_get_lists_per_page || 10;
2775 my $offset = $self->cgi->param('offset') || 0;
2777 $ctx->{bookbags_limit} = $limit;
2778 $ctx->{bookbags_offset} = $offset;
2780 # for list item pagination
2781 my $item_limit = $self->_get_items_per_page;
2782 my $item_page = $self->cgi->param('item_page') || 1;
2783 my $item_offset = ($item_page - 1) * $item_limit;
2784 $ctx->{bookbags_item_page} = $item_page;
2786 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2787 $e->xact_begin; # replication...
2789 my $rv = $self->load_mylist;
2790 unless($rv eq Apache2::Const::OK) {
2795 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2797 {owner => $e->requestor->id, btype => 'bookbag'}, {
2798 order_by => {cbreb => 'name'},
2806 if(!$ctx->{bookbags}) {
2808 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2811 # We load the user prefs to get their default bookbag.
2812 $self->_load_user_with_prefs;
2814 # We also want a total count of the user's bookbags.
2816 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2818 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2820 my $r = $e->json_query($q);
2821 $ctx->{bookbag_count} = $r->[0]->{'count'};
2823 # If the user wants a specific bookbag's items, load them.
2825 if ($self->cgi->param("bbid")) {
2827 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2830 my $query = $self->_prepare_bookbag_container_query(
2831 $bookbag->id, $sorter, $modifier
2834 # Calculate total count of the items in selected bookbag.
2835 # This total includes record entries that have no assets available.
2836 my $bb_search_results = $U->simplereq(
2837 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2838 {"limit" => 1, "offset" => 0}, $query
2839 ); # we only need the count, so do the actual search with limit=1
2841 if ($bb_search_results) {
2842 $ctx->{bb_item_count} = $bb_search_results->{count};
2844 $logger->warn("search failed in load_myopac_bookbags()");
2845 $ctx->{bb_item_count} = 0; # fallback value
2848 #calculate page count
2849 $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2851 if ( ($self->cgi->param("action") || '') eq "editmeta") {
2852 if (!$self->_update_bookbag_metadata($bookbag)) {
2854 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2857 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2860 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2861 if ($self->cgi->param($param)) {
2862 my @vals = $self->cgi->param($param);
2863 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2867 return $self->generic_redirect($url);
2871 # we're done with our CStoreEditor. Rollback here so
2872 # later calls don't cause a timeout, resulting in a
2873 # transaction rollback under the covers.
2877 # For list items pagination
2879 "limit" => $item_limit,
2880 "offset" => $item_offset
2883 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2884 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2886 # capture pref_ou for callnumber filter/display
2887 $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2889 # search for local callnumbers for display
2890 my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2892 my (undef, @recs) = $self->get_records_and_facets(
2893 [ map {$_->target_biblio_record_entry->id} @$items ],
2896 flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2898 site => $ctx->{get_aou}->($focus_ou)->shortname,
2899 pref_lib => $ctx->{pref_ou}
2903 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2905 $bookbag->items($items);
2909 # If we have add_rec, we got here from the "Add to new list"
2910 # or "See all" popmenu items.
2911 if (my $add_rec = $self->cgi->param('add_rec')) {
2912 $self->ctx->{add_rec} = $add_rec;
2913 # But not in the staff client, 'cause that breaks things.
2914 unless ($self->ctx->{is_staff}) {
2915 # allow caller to provide the where_from in cases where
2916 # the referer is an intermediate error page
2917 if ($self->cgi->param('where_from')) {
2918 $self->ctx->{where_from} = $self->cgi->param('where_from');
2920 $self->ctx->{where_from} = $self->ctx->{referer};
2921 if ( my $anchor = $self->cgi->param('anchor') ) {
2922 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2928 # this rollback may be a dupe, but that's OK because
2929 # cstoreditor ignores dupe rollbacks
2932 return Apache2::Const::OK;
2936 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
2937 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2938 sub load_myopac_bookbag_update {
2939 my ($self, $action, $list_id, @hold_recs) = @_;
2940 my $e = $self->editor;
2941 my $cgi = $self->cgi;
2943 # save_notes is effectively another action, but is passed in a separate
2944 # CGI parameter for what are really just layout reasons.
2945 $action = 'save_notes' if $cgi->param('save_notes');
2946 $action ||= $cgi->param('action');
2948 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2950 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2951 my @selected_item = $cgi->param('selected_item');
2952 my $shared = $cgi->param('shared');
2953 my $move_cart = $cgi->param('move_cart');
2954 my $name = $cgi->param('name');
2955 my $description = $cgi->param('description');
2959 # bail out if user is attempting an action that requires
2960 # that at least one list item be selected
2961 if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
2962 ($action eq 'place_hold' || $action eq 'print' ||
2963 $action eq 'email' || $action eq 'del_item')) {
2964 my $url = $self->ctx->{referer};
2965 $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
2966 return $self->generic_redirect($url);
2969 # This url intentionally leaves off the edit_notes parameter, but
2970 # may need to add some back in for paging.
2972 my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2973 $self->ctx->{opac_root} . "/myopac/lists?";
2975 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2976 if ($cgi->param($param)) {
2977 my @vals = $cgi->param($param);
2978 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2982 if ($action eq 'create') {
2985 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2987 $list->description($description);
2988 $list->owner($e->requestor->id);
2989 $list->btype('bookbag');
2990 $list->pub($shared ? 't' : 'f');
2991 $success = $U->simplereq('open-ils.actor',
2992 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2993 if (ref($success) ne 'HASH') {
2994 $list_id = (ref($success)) ? $success->id : $success;
2995 if (scalar @add_rec) {
2996 foreach my $add_rec (@add_rec) {
2997 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2998 $item->bucket($list_id);
2999 $item->target_biblio_record_entry($add_rec);
3000 $success = $U->simplereq('open-ils.actor',
3001 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3002 last unless $success;
3006 my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3007 foreach my $add_rec (@$list) {
3008 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3009 $item->bucket($list_id);
3010 $item->target_biblio_record_entry($add_rec);
3011 $success = $U->simplereq('open-ils.actor',
3012 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3013 last unless $success;
3015 $self->clear_anon_cache;
3018 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3021 $self->ctx->{bucket_failure_noname} = 1;
3024 } elsif($action eq 'place_hold') {
3026 # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3027 my $from_basket = scalar(@hold_recs);
3028 unless (@hold_recs) {
3029 if (@selected_item) {
3030 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3031 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3035 return Apache2::Const::OK unless @hold_recs;
3036 $logger->info("placing holds from list page on: @hold_recs");
3038 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3039 $url .= ';hold_target=' . $_ for @hold_recs;
3040 $url .= ';from_basket=1' if $from_basket;
3041 foreach my $param (('loc', 'qtype', 'query')) {
3042 if ($cgi->param($param)) {
3043 my @vals = $cgi->param($param);
3044 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3047 return $self->generic_redirect($url);
3049 } elsif ($action eq 'print') {
3050 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3051 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3052 if (!$incoming_sort) {
3053 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3055 if (!$incoming_sort) {
3056 $incoming_sort = 'author';
3059 $incoming_sort =~ s/sort.*$//;
3061 $self->ctx->{sort} = $incoming_sort;
3062 $self->ctx->{sort_dir} = $sort_dir;
3064 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3065 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3066 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3067 return $self->load_mylist_print($temp_cache_key);
3068 } elsif ($action eq 'email') {
3069 my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3070 $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3071 if (!$incoming_sort) {
3072 ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3074 if (!$incoming_sort) {
3075 $incoming_sort = 'author';
3078 $incoming_sort =~ s/sort.*$//;
3080 $self->ctx->{sort} = $incoming_sort;
3081 $self->ctx->{sort_dir} = $sort_dir;
3083 my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3084 my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3085 my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3086 return $self->load_mylist_email($temp_cache_key);
3089 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3091 return Apache2::Const::HTTP_BAD_REQUEST unless
3092 $list and $list->owner == $e->requestor->id;
3095 if($action eq 'delete') {
3096 $success = $U->simplereq('open-ils.actor',
3097 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3099 # We check to see if we're deleting the user's default list.
3100 $self->_load_user_with_prefs;
3101 my $settings_map = $self->ctx->{user_setting_map};
3102 if ($$settings_map{'opac.default_list'} == $list_id) {
3103 # We unset the user's opac.default_list setting.
3104 $success = $U->simplereq(
3106 'open-ils.actor.patron.settings.update',
3109 { 'opac.default_list' => 0 }
3113 } elsif($action eq 'show') {
3114 unless($U->is_true($list->pub)) {
3116 $success = $U->simplereq('open-ils.actor',
3117 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3120 } elsif($action eq 'hide') {
3121 if($U->is_true($list->pub)) {
3123 $success = $U->simplereq('open-ils.actor',
3124 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3127 } elsif($action eq 'rename') {
3130 $success = $U->simplereq('open-ils.actor',
3131 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3134 } elsif($action eq 'add_rec') {
3135 foreach my $add_rec (@add_rec) {
3136 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3137 $item->bucket($list_id);
3138 $item->target_biblio_record_entry($add_rec);
3139 $success = $U->simplereq('open-ils.actor',
3140 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3141 last unless $success;
3143 # Redirect back where we came from if we have an anchor parameter:
3144 if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3145 $url = $self->ctx->{referer};
3146 $url =~ s/#.*|$/#$anchor/;
3147 } elsif ($cgi->param('where_from')) {
3148 # Or, if we have a "where_from" parameter.
3149 $url = $cgi->param('where_from');
3151 } elsif ($action eq 'del_item') {
3152 foreach (@selected_item) {
3153 $success = $U->simplereq(
3155 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3157 last unless $success;
3159 } elsif ($action eq 'save_notes') {
3160 $success = $self->update_bookbag_item_notes;
3161 $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3162 } elsif ($action eq 'make_default') {
3163 $success = $U->simplereq(
3165 'open-ils.actor.patron.settings.update',
3168 { 'opac.default_list' => $list_id }
3170 } elsif ($action eq 'remove_default') {
3171 $success = $U->simplereq(
3173 'open-ils.actor.patron.settings.update',
3176 { 'opac.default_list' => 0 }
3180 return $self->generic_redirect($url) if $success;
3182 $self->ctx->{where_from} = $cgi->param('where_from');
3183 $self->ctx->{bucket_action} = $action;
3184 $self->ctx->{bucket_action_failed} = 1;
3185 return Apache2::Const::OK;
3188 sub update_bookbag_item_notes {
3190 my $e = $self->editor;
3192 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3193 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3195 # We're going to leverage an API call that's already been written to check
3196 # permissions appropriately.
3198 my $a = create OpenSRF::AppSession("open-ils.actor");
3199 my $method = "open-ils.actor.container.item_note.cud";
3201 for my $note_key (@note_keys) {
3204 my $id = ($note_key =~ /(\d+)/)[0];
3207 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3208 my $event = $e->die_event;
3209 $self->apache->log->warn(
3210 "error retrieving cbrebin id $id, got event " .
3214 $self->ctx->{bucket_action_event} = $event;
3218 if (length($self->cgi->param($note_key))) {
3219 $note->ischanged(1);
3220 $note->note($self->cgi->param($note_key));
3222 $note->isdeleted(1);
3225 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3227 if (defined $U->event_code($r)) {
3228 $self->apache->log->warn(
3229 "attempt to modify cbrebin " . $note->id .
3230 " returned event " . $r->{textcode}
3234 $self->ctx->{bucket_action_event} = $r;
3239 for my $item_key (@item_keys) {
3240 my $id = int(($item_key =~ /(\d+)/)[0]);
3241 my $text = $self->cgi->param($item_key);
3244 next unless length $text;
3246 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3251 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3253 if (defined $U->event_code($r)) {
3254 $self->apache->log->warn(
3255 "attempt to create cbrebin for item " . $note->item .
3256 " returned event " . $r->{textcode}
3260 $self->ctx->{bucket_action_event} = $r;
3269 sub load_myopac_bookbag_print {
3272 my $id = int($self->cgi->param("list"));
3274 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3277 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3281 # Get the bookbag object itself, assuming we're allowed to.
3282 if ($self->editor->allowed("VIEW_CONTAINER")) {
3284 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3286 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3290 "owner" => $self->editor->requestor->id,
3294 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3296 $bbag = pop @$bookbags;
3299 # If we have a bookbag we're allowed to look at, issue the A/T event
3300 # to get CSV, passing as a user param that search query we built before.
3302 $self->ctx->{csv} = $U->fire_object_event(
3303 undef, "container.biblio_record_entry_bucket.csv",
3304 $bbag, $self->editor->requestor->home_ou,
3305 undef, {"item_search" => $item_search}
3309 # Create a reasonable filename and set the content disposition to
3310 # provoke browser download dialogs.
3311 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3313 return $self->set_file_download_headers("$filename.csv");
3316 sub load_myopac_circ_history_export {
3318 my $e = $self->editor;
3319 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3321 my $circs = $self->fetch_user_circ_history(1);
3323 $self->ctx->{csv}->{circs} = $circs;
3324 return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3328 sub load_myopac_reservations {
3330 my $e = $self->editor;
3331 my $ctx = $self->ctx;
3333 my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3334 $e->authtoken, undef
3337 $ctx->{reservations} = $upcoming;
3338 return Apache2::Const::OK;
3342 sub load_password_reset {
3344 my $cgi = $self->cgi;
3345 my $ctx = $self->ctx;
3346 my $barcode = $cgi->param('barcode');
3347 my $username = $cgi->param('username');
3348 my $email = $cgi->param('email');
3349 my $pwd1 = $cgi->param('pwd1');
3350 my $pwd2 = $cgi->param('pwd2');
3351 my $uuid = $ctx->{page_args}->[0];
3355 $logger->info("patron password reset with uuid $uuid");
3357 if ($pwd1 and $pwd2) {
3359 if ($pwd1 eq $pwd2) {
3361 my $response = $U->simplereq(
3363 'open-ils.actor.patron.password_reset.commit',
3366 $logger->info("patron password reset response " . Dumper($response));
3368 if ($U->event_code($response)) { # non-success event
3370 my $code = $response->{textcode};
3372 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3373 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3376 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3377 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3382 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3385 } else { # passwords not equal
3387 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3390 } else { # 2 password values needed
3392 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3395 } elsif ($barcode or $username) {
3397 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3398 push(@params, $email) if $email;
3402 'open-ils.actor.patron.password_reset.request', @params);
3404 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3407 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3408 return Apache2::Const::OK;