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;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Cache;
11 use Digest::MD5 qw(md5_hex);
13 $Data::Dumper::Indent = 0;
15 my $U = 'OpenILS::Application::AppUtils';
17 sub prepare_extended_user_info {
20 my $e = $self->editor;
22 # are we already in a transaction?
23 my $local_xact = !$e->{xact_id};
24 $e->xact_begin if $local_xact;
26 $self->ctx->{user} = $self->editor->retrieve_actor_user([
27 $self->ctx->{user}->id,
31 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
37 $e->rollback if $local_xact;
39 # discard replaced (negative-id) addresses.
40 $self->ctx->{user}->addresses([
41 grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
43 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
44 unless $self->ctx->{user};
49 # Given an event returned by a failed attempt to create a hold, do we have
50 # permission to override? XXX Should the permission check be scoped to a
51 # given org_unit context?
52 sub test_could_override {
53 my ($self, $event) = @_;
55 return 0 unless $event;
56 return 1 if $self->editor->allowed($event->{textcode} . ".override");
57 return 1 if $event->{"fail_part"} and
58 $self->editor->allowed($event->{"fail_part"} . ".override");
62 # Find out whether we care that local copies are available
63 sub local_avail_concern {
64 my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
66 my $would_block = $self->ctx->{get_org_setting}->
67 ($pickup_lib, "circ.holds.hold_has_copy_at.block");
69 $self->ctx->{get_org_setting}->
70 ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
71 not $self->cgi->param("override")
72 ) unless $would_block;
74 if ($would_block or $would_alert) {
76 "hold_target" => $hold_target,
77 "hold_type" => $hold_type,
78 "org_unit" => $pickup_lib
80 my $local_avail = $U->simplereq(
82 "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
85 "copy availability information for " . Dumper($args) .
86 " is " . Dumper($local_avail)
88 if (%$local_avail) { # if hash not empty
89 $self->ctx->{hold_copy_available} = $local_avail;
90 return ($would_block, $would_alert);
98 # user : au object, fleshed
99 sub load_myopac_prefs {
101 my $cgi = $self->cgi;
102 my $e = $self->editor;
103 my $pending_addr = $cgi->param('pending_addr');
104 my $replace_addr = $cgi->param('replace_addr');
105 my $delete_pending = $cgi->param('delete_pending');
107 $self->prepare_extended_user_info;
108 my $user = $self->ctx->{user};
110 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
111 if($lock_usernames == 1) {
112 # Policy says no username changes
113 $self->ctx->{username_change_disallowed} = 1;
115 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
116 if($username_unlimit != 1) {
117 my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
119 # Default is "starts with a number"
120 $regex_check = '^\d+';
122 # You already have a username?
123 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
124 $self->ctx->{username_change_disallowed} = 1;
129 return Apache2::Const::OK unless
130 $pending_addr or $replace_addr or $delete_pending;
132 my @form_fields = qw/address_type street1 street2 city county state country post_code/;
135 if( $pending_addr ) { # update an existing pending address
137 ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
138 return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
139 $paddr->$_( $cgi->param($_) ) for @form_fields;
141 } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
143 $paddr = Fieldmapper::actor::user_address->new;
145 $paddr->usr($user->id);
146 $paddr->pending('t');
147 $paddr->replaces($replace_addr);
148 $paddr->$_( $cgi->param($_) ) for @form_fields;
150 } elsif( $delete_pending ) {
151 $paddr = $e->retrieve_actor_user_address($delete_pending);
152 return Apache2::Const::HTTP_BAD_REQUEST unless
153 $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
154 $paddr->isdeleted(1);
157 my $resp = $U->simplereq(
159 'open-ils.actor.user.address.pending.cud',
160 $e->authtoken, $paddr);
162 if( $U->event_code($resp) ) {
163 $logger->error("Error updating pending address: $resp");
164 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
167 # in light of these changes, re-fetch latest data
169 $self->prepare_extended_user_info;
172 return Apache2::Const::OK;
175 sub load_myopac_prefs_notify {
177 my $e = $self->editor;
179 my $user_prefs = $self->fetch_optin_prefs;
180 $user_prefs = $self->update_optin_prefs($user_prefs)
181 if $self->cgi->request_method eq 'POST';
183 $self->ctx->{opt_in_settings} = $user_prefs;
186 my $set_map = $self->ctx->{user_setting_map};
190 opac.default_sms_notify
192 my $val = $self->cgi->param($key);
193 $settings{$key}= $val unless $$set_map{$key} eq $val;
196 my $key = 'opac.default_sms_carrier';
197 my $val = $self->cgi->param('sms_carrier');
198 $settings{$key}= $val unless $$set_map{$key} eq $val;
200 $key = 'opac.hold_notify';
201 my @notify_methods = ();
202 if ($self->cgi->param($key . ".email") eq 'on') {
203 push @notify_methods, "email";
205 if ($self->cgi->param($key . ".phone") eq 'on') {
206 push @notify_methods, "phone";
208 if ($self->cgi->param($key . ".sms") eq 'on') {
209 push @notify_methods, "sms";
211 $val = join("|",@notify_methods);
212 $settings{$key}= $val unless $$set_map{$key} eq $val;
214 # Send the modified settings off to be saved
217 'open-ils.actor.patron.settings.update',
218 $self->editor->authtoken, undef, \%settings);
220 # re-fetch user prefs
221 $self->ctx->{updated_user_settings} = \%settings;
222 return $self->_load_user_with_prefs || Apache2::Const::OK;
225 sub fetch_optin_prefs {
227 my $e = $self->editor;
229 # fetch all of the opt-in settings the user has access to
230 # XXX: user's should in theory have options to opt-in to notices
231 # for remote locations, but that opens the door for a large
232 # set of generally un-used opt-ins.. needs discussion
233 my $opt_ins = $U->simplereq(
235 'open-ils.actor.event_def.opt_in.settings.atomic',
236 $e->authtoken, $e->requestor->home_ou);
238 # some opt-ins are staff-only
239 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
241 # fetch user setting values for each of the opt-in settings
242 my $user_set = $U->simplereq(
244 'open-ils.actor.patron.settings.retrieve',
247 [map {$_->name} @$opt_ins]
250 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
253 sub update_optin_prefs {
255 my $user_prefs = shift;
256 my $e = $self->editor;
257 my @settings = $self->cgi->param('setting');
260 # apply now-true settings
261 for my $applied (@settings) {
262 # see if setting is already applied to this user
263 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
264 $newsets{$applied} = OpenSRF::Utils::JSON->true;
267 # remove now-false settings
268 for my $pref (grep { $_->{value} } @$user_prefs) {
269 $newsets{$pref->{cust}->name} = undef
270 unless grep { $_ eq $pref->{cust}->name } @settings;
275 'open-ils.actor.patron.settings.update',
276 $e->authtoken, $e->requestor->id, \%newsets);
278 # update the local prefs to match reality
279 for my $pref (@$user_prefs) {
280 $pref->{value} = $newsets{$pref->{cust}->name}
281 if exists $newsets{$pref->{cust}->name};
287 sub _load_user_with_prefs {
289 my $stat = $self->prepare_extended_user_info('settings');
290 return $stat if $stat; # not-OK
292 $self->ctx->{user_setting_map} = {
293 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
294 @{$self->ctx->{user}->settings}
300 sub _get_bookbag_sort_params {
301 my ($self, $param_name) = @_;
303 # The interface that feeds this cgi parameter will provide a single
304 # argument for a QP sort filter, and potentially a modifier after a period.
305 # In practice this means the "sort" parameter will be something like
306 # "titlesort" or "authorsort.descending".
307 my $sorter = $self->cgi->param($param_name) || "";
310 $sorter =~ s/^(.*?)\.(.*)/$1/;
311 $modifier = $2 || undef;
314 return ($sorter, $modifier);
317 sub _prepare_bookbag_container_query {
318 my ($self, $container_id, $sorter, $modifier) = @_;
321 "container(bre,bookbag,%d,%s)%s%s",
322 $container_id, $self->editor->authtoken,
323 ($sorter ? " sort($sorter)" : ""),
324 ($modifier ? "#$modifier" : "")
328 sub _prepare_anonlist_sorting_query {
329 my ($self, $list, $sorter, $modifier) = @_;
332 "record_list(%s)%s%s",
334 ($sorter ? " sort($sorter)" : ""),
335 ($modifier ? "#$modifier" : "")
340 sub load_myopac_prefs_settings {
345 opac.default_search_location
348 my $stat = $self->_load_user_with_prefs;
349 return $stat if $stat;
351 return Apache2::Const::OK
352 unless $self->cgi->request_method eq 'POST';
354 # some setting values from the form don't match the
355 # required value/format for the db, so they have to be
356 # individually translated.
359 my $set_map = $self->ctx->{user_setting_map};
361 foreach my $key (@user_prefs) {
362 my $val = $self->cgi->param($key);
363 $settings{$key}= $val unless $$set_map{$key} eq $val;
366 my $now = DateTime->now->strftime('%F');
367 foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
368 my $val = $self->cgi->param($key);
369 if($val and $val eq 'on') {
370 # Set the start time to 'now' unless a start time already exists for the user
371 $settings{$key} = $now unless $$set_map{$key};
373 # clear the start time if one previously existed for the user
374 $settings{$key} = undef if $$set_map{$key};
378 # Send the modified settings off to be saved
381 'open-ils.actor.patron.settings.update',
382 $self->editor->authtoken, undef, \%settings);
384 # re-fetch user prefs
385 $self->ctx->{updated_user_settings} = \%settings;
386 return $self->_load_user_with_prefs || Apache2::Const::OK;
389 sub fetch_user_holds {
391 my $hold_ids = shift;
392 my $ids_only = shift;
394 my $available = shift;
398 my $e = $self->editor;
401 my $circ = OpenSRF::AppSession->create('open-ils.circ');
403 $hold_ids = $circ->request(
404 'open-ils.circ.holds.id_list.retrieve.authoritative',
410 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
414 return $hold_ids if $ids_only or @$hold_ids == 0;
417 suppress_notices => 1,
418 suppress_transits => 1,
420 suppress_patron_details => 1
423 # ----------------------------------------------------------------
424 # Collect holds in batches of $batch_size for faster retrieval
428 my $mk_req_batch = sub {
430 my $top_idx = $batch_idx + $batch_size;
431 while($batch_idx < $top_idx) {
432 my $hold_id = $hold_ids->[$batch_idx++];
433 last unless $hold_id;
434 my $ses = OpenSRF::AppSession->create('open-ils.circ');
435 my $req = $ses->request(
436 'open-ils.circ.hold.details.retrieve',
437 $e->authtoken, $hold_id, $args);
438 push(@ses, {ses => $ses, req => $req});
444 my(@collected, @holds, @ses);
447 @ses = $mk_req_batch->() if $first;
448 last if $first and not @ses;
451 # If desired by the caller, filter any holds that are not available.
453 @collected = grep { $_->{hold}->{status} == 4 } @collected;
455 while(my $blob = pop(@collected)) {
456 my (undef, @data) = $self->get_records_and_facets(
457 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
459 $blob->{marc_xml} = $data[0]->{marc_xml};
464 for my $req_data (@ses) {
465 push(@collected, {hold => $req_data->{req}->gather(1)});
466 $req_data->{ses}->kill_me;
469 @ses = $mk_req_batch->();
470 last unless @collected or @ses;
474 # put the holds back into the original server sort order
476 for my $id (@$hold_ids) {
477 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
483 sub handle_hold_update {
486 my $hold_ids = shift;
487 my $e = $self->editor;
490 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
491 @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
493 my $circ = OpenSRF::AppSession->create('open-ils.circ');
495 if($action =~ /cancel/) {
497 for my $hold_id (@hold_ids) {
498 my $resp = $circ->request(
499 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
502 } elsif ($action =~ /activate|suspend/) {
505 for my $hold_id (@hold_ids) {
506 my $vals = {id => $hold_id};
508 if($action =~ /activate/) {
509 $vals->{frozen} = 'f';
510 $vals->{thaw_date} = undef;
512 } elsif($action =~ /suspend/) {
513 $vals->{frozen} = 't';
514 # $vals->{thaw_date} = TODO;
516 push(@$vlist, $vals);
519 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
520 $self->ctx->{hold_suspend_post_capture} = 1 if
521 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
523 } elsif ($action eq 'edit') {
526 my $val = {"id" => $_};
527 $val->{"frozen"} = $self->cgi->param("frozen");
528 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
530 for my $field (qw/expire_time thaw_date/) {
531 # XXX TODO make this support other date formats, not just
533 next unless $self->cgi->param($field) =~
534 m:^(\d{2})/(\d{2})/(\d{4})$:;
535 $val->{$field} = "$3-$1-$2";
541 'open-ils.circ.hold.update.batch.atomic',
542 $e->authtoken, undef, \@vals
543 )->gather(1); # LFW XXX test for failure
544 $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
545 foreach my $param (('loc', 'qtype', 'query')) {
546 if ($self->cgi->param($param)) {
547 $url .= ";$param=" . uri_escape($self->cgi->param($param));
553 return defined($url) ? $self->generic_redirect($url) : undef;
556 sub load_myopac_holds {
558 my $e = $self->editor;
559 my $ctx = $self->ctx;
561 my $limit = $self->cgi->param('limit') || 0;
562 my $offset = $self->cgi->param('offset') || 0;
563 my $action = $self->cgi->param('action') || '';
564 my $hold_id = $self->cgi->param('id');
565 my $available = int($self->cgi->param('available') || 0);
567 my $hold_handle_result;
568 $hold_handle_result = $self->handle_hold_update($action) if $action;
570 $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
572 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
577 sub load_place_hold {
579 my $ctx = $self->ctx;
580 my $gos = $ctx->{get_org_setting};
581 my $e = $self->editor;
582 my $cgi = $self->cgi;
584 $self->ctx->{page} = 'place_hold';
585 my @targets = $cgi->param('hold_target');
586 my @parts = $cgi->param('part');
588 $ctx->{hold_type} = $cgi->param('hold_type');
589 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
590 $ctx->{email_notify} = $cgi->param('email_notify');
591 if ($cgi->param('phone_notify_checkbox')) {
592 $ctx->{phone_notify} = $cgi->param('phone_notify');
594 if ($cgi->param('sms_notify_checkbox')) {
595 $ctx->{sms_notify} = $cgi->param('sms_notify');
596 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
599 return $self->generic_redirect unless @targets;
601 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
603 # if the staff client provides a patron barcode, fetch the patron
604 if (my $bc = $self->cgi->cookie("patron_barcode")) {
605 $ctx->{patron_recipient} = $U->simplereq(
606 "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
607 $self->editor->authtoken, $bc
608 ) or return Apache2::Const::HTTP_BAD_REQUEST;
610 $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
612 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
620 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
622 my $user_setting_map = {
623 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
625 $ctx->{patron_recipient}
626 ? $ctx->{patron_recipient}->settings
627 : $ctx->{staff_recipient}->settings
630 $ctx->{user_setting_map} = $user_setting_map;
632 my $default_notify = $$user_setting_map{'opac.hold_notify'} || '';
633 if ($default_notify =~ /email/) {
634 $ctx->{default_email_notify} = 'checked';
636 $ctx->{default_email_notify} = '';
638 if ($default_notify =~ /phone/) {
639 $ctx->{default_phone_notify} = 'checked';
641 $ctx->{default_phone_notify} = '';
643 if ($default_notify =~ /sms/) {
644 $ctx->{default_sms_notify} = 'checked';
646 $ctx->{default_sms_notify} = '';
649 my $request_lib = $e->requestor->ws_ou;
651 $ctx->{hold_data} = \@hold_data;
655 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
656 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
657 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
658 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
662 my $type_dispatch = {
664 my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
666 for my $id (@targets) { # force back into the correct order
667 my ($rec) = grep {$_->id eq $id} @$recs;
669 # NOTE: if tpac ever supports locked-down pickup libs,
670 # we'll need to pass a pickup_lib param along with the
671 # record to filter the set of monographic parts.
672 my $parts = $U->simplereq(
674 'open-ils.search.biblio.record_hold_parts',
678 # T holds on records that have parts are OK, but if the record has
679 # no non-part copies, the hold will ultimately fail. When that
680 # happens, require the user to select a part.
681 my $part_required = 0;
683 my $np_copies = $e->json_query({
684 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
685 from => {acp => {acn => {}, acpm => {type => 'left'}}},
687 '+acp' => {deleted => 'f'},
688 '+acn' => {deleted => 'f', record => $rec->id},
689 '+acpm' => {id => undef}
692 $part_required = 1 if $np_copies->[0]->{count} == 0;
695 push(@hold_data, $data_filler->({
699 part_required => $part_required
704 my $vols = $e->batch_retrieve_asset_call_number([
707 "flesh_fields" => {"acn" => ["record"]}
709 ], {substream => 1});
711 for my $id (@targets) {
712 my ($vol) = grep {$_->id eq $id} @$vols;
713 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
717 my $copies = $e->batch_retrieve_asset_copy([
722 "acp" => ["call_number"]
725 ], {substream => 1});
727 for my $id (@targets) {
728 my ($copy) = grep {$_->id eq $id} @$copies;
729 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
733 my $isses = $e->batch_retrieve_serial_issuance([
737 "siss" => ["subscription"], "ssub" => ["record_entry"]
740 ], {substream => 1});
742 for my $id (@targets) {
743 my ($iss) = grep {$_->id eq $id} @$isses;
744 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
749 }->{$ctx->{hold_type}}->();
751 # caller sent bad target IDs or the wrong hold type
752 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
754 # generate the MARC xml for each record
755 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
757 my $pickup_lib = $cgi->param('pickup_lib');
758 # no pickup lib means no holds placement
759 return Apache2::Const::OK unless $pickup_lib;
761 $ctx->{hold_attempt_made} = 1;
763 # Give the original CGI params back to the user in case they
764 # want to try to override something.
765 $ctx->{orig_params} = $cgi->Vars;
766 delete $ctx->{orig_params}{submit};
767 delete $ctx->{orig_params}{hold_target};
768 delete $ctx->{orig_params}{part};
770 my $usr = $e->requestor->id;
772 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
773 # find the real hold target
775 $usr = $U->simplereq(
777 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
778 $e->authtoken, $cgi->param("hold_usr"));
780 if (defined $U->event_code($usr)) {
781 $ctx->{hold_failed} = 1;
782 $ctx->{hold_failed_event} = $usr;
786 # target_id is the true target_id for holds placement.
787 # needed for attempt_hold_placement()
788 # With the exception of P-type holds, target_id == target->id.
789 $_->{target_id} = $_->{target}->id for @hold_data;
791 if ($ctx->{hold_type} eq 'T') {
793 # Much like quantum wave-particles, P-type holds pop into
794 # and out of existence at the user's whim. For our purposes,
795 # we treat such holds as T(itle) holds with a selected_part
796 # designation. When the time comes to pass the hold information
797 # off for holds possibility testing and placement, make it look
798 # like a real P-type hold.
799 my (@p_holds, @t_holds);
801 for my $idx (0..$#parts) {
802 my $hdata = $hold_data[$idx];
803 if (my $part = $parts[$idx]) {
804 $hdata->{target_id} = $part;
805 $hdata->{selected_part} = $part;
806 push(@p_holds, $hdata);
808 push(@t_holds, $hdata);
812 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
813 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
816 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
819 # NOTE: we are leaving the staff-placed patron barcode cookie
820 # in place. Otherwise, it's not possible to place more than
821 # one hold for the patron within a staff/patron session. This
822 # does leave the barcode to linger longer than is ideal, but
823 # normal staff work flow will cause the cookie to be replaced
824 # with each new patron anyway.
825 # TODO: See about getting the staff client to clear the cookie
827 # return to the place_hold page so the results of the hold
828 # placement attempt can be reported to the user
829 return Apache2::Const::OK;
832 sub attempt_hold_placement {
833 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
834 my $cgi = $self->cgi;
835 my $ctx = $self->ctx;
836 my $e = $self->editor;
838 # First see if we should warn/block for any holds that
839 # might have locally available items.
840 for my $hdata (@hold_data) {
841 my ($local_block, $local_alert) = $self->local_avail_concern(
842 $hdata->{target_id}, $hold_type, $pickup_lib);
845 $hdata->{hold_failed} = 1;
846 $hdata->{hold_local_block} = 1;
847 } elsif ($local_alert) {
848 $hdata->{hold_failed} = 1;
849 $hdata->{hold_local_alert} = 1;
853 my $method = 'open-ils.circ.holds.test_and_create.batch';
854 $method .= '.override' if $cgi->param('override');
856 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
858 if(@create_targets) {
860 my $bses = OpenSRF::AppSession->create('open-ils.circ');
861 my $breq = $bses->request(
864 $data_filler->({ patronid => $usr,
865 pickup_lib => $pickup_lib,
866 hold_type => $hold_type
871 while (my $resp = $breq->recv) {
873 $resp = $resp->content;
874 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
876 if ($U->event_code($resp)) {
877 $ctx->{general_hold_error} = $resp;
881 my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
882 my $result = $resp->{result};
884 if ($U->event_code($result)) {
885 # e.g. permission denied
886 $hdata->{hold_failed} = 1;
887 $hdata->{hold_failed_event} = $result;
891 if(not ref $result and $result > 0) {
892 # successul hold returns the hold ID
894 $hdata->{hold_success} = $result;
897 # hold-specific failure event
898 $hdata->{hold_failed} = 1;
900 if (ref $result eq 'HASH') {
901 $hdata->{hold_failed_event} = $result->{last_event};
903 if ($result->{age_protected_copy}) {
904 $hdata->{could_override} = 1;
905 $hdata->{age_protect} = 1;
907 $hdata->{could_override} = $self->test_could_override($hdata->{hold_failed_event});
909 } elsif (ref $result eq 'ARRAY') {
910 $hdata->{hold_failed_event} = $result->[0];
912 if ($result->[3]) { # age_protect_only
913 $hdata->{could_override} = 1;
914 $hdata->{age_protect} = 1;
916 $hdata->{could_override} = $self->test_could_override($hdata->{hold_failed_event});
927 sub fetch_user_circs {
929 my $flesh = shift; # flesh bib data, etc.
930 my $circ_ids = shift;
934 my $e = $self->editor;
939 @circ_ids = @$circ_ids;
944 select => {circ => ['id']},
948 usr => $e->requestor->id,
949 checkin_time => undef,
951 {stop_fines => undef},
952 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
956 order_by => {circ => ['due_date']}
959 $query->{limit} = $limit if $limit;
960 $query->{offset} = $offset if $offset;
962 my $ids = $e->json_query($query);
963 @circ_ids = map {$_->{id}} @$ids;
966 return [] unless @circ_ids;
971 circ => ['target_copy'],
972 acp => ['call_number'],
978 my $circs = $e->search_action_circulation(
979 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
982 for my $circ (@$circs) {
985 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
986 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
987 undef # pre-cat copy, use the dummy title/author instead
992 # make sure the final list is in the correct order
994 for my $id (@circ_ids) {
997 (grep { $_->{circ}->id == $id } @circs)
1001 return \@sorted_circs;
1005 sub handle_circ_renew {
1008 my $ctx = $self->ctx;
1010 my @renew_ids = $self->cgi->param('circ');
1012 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1014 # TODO: fire off renewal calls in batches to speed things up
1016 for my $circ (@$circs) {
1018 my $evt = $U->simplereq(
1020 'open-ils.circ.renew',
1021 $self->editor->authtoken,
1023 patron_id => $self->editor->requestor->id,
1024 copy_id => $circ->{circ}->target_copy,
1029 # TODO return these, then insert them into the circ data
1030 # blob that is shoved into the template for each circ
1031 # so the template won't have to match them
1032 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1039 sub load_myopac_circs {
1041 my $e = $self->editor;
1042 my $ctx = $self->ctx;
1045 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1046 my $offset = $self->cgi->param('offset') || 0;
1047 my $action = $self->cgi->param('action') || '';
1049 # perform the renewal first if necessary
1050 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1052 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1054 my $success_renewals = 0;
1055 my $failed_renewals = 0;
1056 for my $data (@{$ctx->{circs}}) {
1057 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1060 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1061 $data->{renewal_response} = $evt;
1062 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1063 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1067 $ctx->{success_renewals} = $success_renewals;
1068 $ctx->{failed_renewals} = $failed_renewals;
1070 return Apache2::Const::OK;
1073 sub load_myopac_circ_history {
1075 my $e = $self->editor;
1076 my $ctx = $self->ctx;
1077 my $limit = $self->cgi->param('limit') || 15;
1078 my $offset = $self->cgi->param('offset') || 0;
1080 $ctx->{circ_history_limit} = $limit;
1081 $ctx->{circ_history_offset} = $offset;
1083 my $circ_ids = $e->json_query({
1087 transform => 'action.usr_visible_circs',
1088 result_field => 'id'
1092 where => {id => $e->requestor->id},
1097 $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1098 return Apache2::Const::OK;
1101 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1102 sub load_myopac_hold_history {
1104 my $e = $self->editor;
1105 my $ctx = $self->ctx;
1106 my $limit = $self->cgi->param('limit') || 15;
1107 my $offset = $self->cgi->param('offset') || 0;
1108 $ctx->{hold_history_limit} = $limit;
1109 $ctx->{hold_history_offset} = $offset;
1111 my $hold_ids = $e->json_query({
1115 transform => 'action.usr_visible_holds',
1116 result_field => 'id'
1120 where => {id => $e->requestor->id},
1125 $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
1126 return Apache2::Const::OK;
1129 sub load_myopac_payment_form {
1133 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1134 $r = $self->prepare_extended_user_info and return $r;
1136 return Apache2::Const::OK;
1139 # TODO: add other filter options as params/configs/etc.
1140 sub load_myopac_payments {
1142 my $limit = $self->cgi->param('limit') || 20;
1143 my $offset = $self->cgi->param('offset') || 0;
1144 my $e = $self->editor;
1146 $self->ctx->{payment_history_limit} = $limit;
1147 $self->ctx->{payment_history_offset} = $offset;
1150 $args->{limit} = $limit if $limit;
1151 $args->{offset} = $offset if $offset;
1153 if (my $max_age = $self->ctx->{get_org_setting}->(
1154 $e->requestor->home_ou, "opac.payment_history_age_limit"
1156 my $min_ts = DateTime->now(
1157 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1158 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1160 $logger->info("XXX min_ts: $min_ts");
1161 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1164 $self->ctx->{payments} = $U->simplereq(
1166 'open-ils.actor.user.payments.retrieve.atomic',
1167 $e->authtoken, $e->requestor->id, $args);
1169 return Apache2::Const::OK;
1172 # 1. caches the form parameters
1173 # 2. loads the credit card payment "Processing..." page
1174 sub load_myopac_pay_init {
1176 my $cache = OpenSRF::Utils::Cache->new('global');
1178 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1180 return $self->generic_redirect unless @payment_xacts;
1182 my $cc_args = {"where_process" => 1};
1184 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1185 number cvv2 expire_year expire_month billing_first
1186 billing_last billing_address billing_city billing_state
1191 cc_args => $cc_args,
1192 user => $self->ctx->{user}->id,
1193 xacts => \@payment_xacts
1196 # generate a temporary cache token and cache the form data
1197 my $token = md5_hex($$ . time() . rand());
1198 $cache->put_cache($token, $cache_args, 30);
1200 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1202 # after we render the processing page, we quickly redirect to submit
1203 # the actual payment. The refresh url contains the payment token.
1204 # It also contains the list of xact IDs, which allows us to clear the
1205 # cache at the earliest possible time while leaving a trace of which
1206 # transactions we were processing, so the UI can bring the user back
1207 # to the payment form w/ the same xacts if the payment fails.
1209 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1210 $refresh .= ";xact=$_" for @payment_xacts;
1211 $self->ctx->{refresh} = $refresh;
1213 return Apache2::Const::OK;
1216 # retrieve the cached CC payment info and send off for processing
1217 sub load_myopac_pay {
1219 my $token = $self->ctx->{page_args}->[0];
1220 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1222 my $cache = OpenSRF::Utils::Cache->new('global');
1223 my $cache_args = $cache->get_cache($token);
1224 $cache->delete_cache($token);
1226 # this page is loaded immediately after the token is created.
1227 # if the cached data is not there, it's because of an invalid
1228 # token (or cache failure) and not because of a timeout.
1229 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1231 my @payment_xacts = @{$cache_args->{xacts}};
1232 my $cc_args = $cache_args->{cc_args};
1234 # as an added security check, verify the user submitting
1235 # the form is the same as the user whose data was cached
1236 return Apache2::Const::HTTP_BAD_REQUEST unless
1237 $cache_args->{user} == $self->ctx->{user}->id;
1239 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1242 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1244 # balance_owed is computed specifically from the fines we're paying
1245 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1246 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1247 return Apache2::Const::HTTP_BAD_REQUEST;
1251 "cc_args" => $cc_args,
1252 "userid" => $self->ctx->{user}->id,
1253 "payment_type" => "credit_card_payment",
1254 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1257 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1258 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1261 $self->ctx->{"payment_response"} = $resp;
1263 unless ($resp->{"textcode"}) {
1264 $self->ctx->{printable_receipt} = $U->simplereq(
1265 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1266 $self->editor->authtoken, $resp->{payments}
1270 return Apache2::Const::OK;
1273 sub load_myopac_receipt_print {
1276 $self->ctx->{printable_receipt} = $U->simplereq(
1277 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1278 $self->editor->authtoken, [$self->cgi->param("payment")]
1281 return Apache2::Const::OK;
1284 sub load_myopac_receipt_email {
1287 # The following ML method doesn't actually check whether the user in
1288 # question has an email address, so we do.
1289 if ($self->ctx->{user}->email) {
1290 $self->ctx->{email_receipt_result} = $U->simplereq(
1291 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1292 $self->editor->authtoken, [$self->cgi->param("payment")]
1295 $self->ctx->{email_receipt_result} =
1296 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1299 return Apache2::Const::OK;
1303 my ($self, $limit, $offset, $id_list) = @_;
1305 # XXX TODO: check for failure after various network calls
1307 # It may be unclear, but this result structure lumps circulation and
1308 # reservation fines together, and keeps grocery fines separate.
1309 $self->ctx->{"fines"} = {
1310 "circulation" => [],
1317 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1319 # TODO: This should really be a ML call, but the existing calls
1320 # return an excessive amount of data and don't offer streaming
1322 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1324 my $req = $cstore->request(
1325 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1327 usr => $self->editor->requestor->id,
1328 balance_owed => {'!=' => 0},
1329 ($id_list && @$id_list ? ("id" => $id_list) : ()),
1334 mobts => [qw/grocery circulation reservation/],
1335 bresv => ['target_resource_type'],
1339 circ => ['target_copy'],
1340 acp => ['call_number'],
1343 order_by => { mobts => 'xact_start' },
1348 my @total_keys = qw/total_paid total_owed balance_owed/;
1349 $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1351 while(my $resp = $req->recv) {
1352 my $mobts = $resp->content;
1353 my $circ = $mobts->circulation;
1356 if($mobts->grocery) {
1357 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1358 $last_billing = pop(@billings);
1361 # XXX TODO confirm that the following, and the later division by 100.0
1362 # to get a floating point representation once again, is sufficiently
1363 # "money-safe" math.
1364 $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1366 my $marc_xml = undef;
1367 if ($mobts->xact_type eq 'reservation' and
1368 $mobts->reservation->target_resource_type->record) {
1369 $marc_xml = XML::LibXML->new->parse_string(
1370 $mobts->reservation->target_resource_type->record->marc
1372 } elsif ($mobts->xact_type eq 'circulation' and
1373 $circ->target_copy->call_number->id != -1) {
1374 $marc_xml = XML::LibXML->new->parse_string(
1375 $circ->target_copy->call_number->record->marc
1380 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1383 last_grocery_billing => $last_billing,
1384 marc_xml => $marc_xml
1391 $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1395 sub prepare_fines_for_payment {
1396 # This assumes $self->prepare_fines has already been run
1400 if ($self->ctx->{fines}) {
1401 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1402 @{$self->ctx->{fines}->{circulation}},
1403 @{$self->ctx->{fines}->{grocery}}
1410 sub load_myopac_main {
1412 my $limit = $self->cgi->param('limit') || 0;
1413 my $offset = $self->cgi->param('offset') || 0;
1414 $self->ctx->{search_ou} = $self->_get_search_lib();
1416 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1419 sub load_myopac_update_email {
1421 my $e = $self->editor;
1422 my $ctx = $self->ctx;
1423 my $email = $self->cgi->param('email') || '';
1424 my $current_pw = $self->cgi->param('current_pw') || '';
1426 # needed for most up-to-date email address
1427 if (my $r = $self->prepare_extended_user_info) { return $r };
1429 return Apache2::Const::OK
1430 unless $self->cgi->request_method eq 'POST';
1432 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1433 $ctx->{invalid_email} = $email;
1434 return Apache2::Const::OK;
1437 my $stat = $U->simplereq(
1439 'open-ils.actor.user.email.update',
1440 $e->authtoken, $email, $current_pw);
1442 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1443 $ctx->{password_incorrect} = 1;
1444 return Apache2::Const::OK;
1447 unless ($self->cgi->param("redirect_to")) {
1448 my $url = $self->apache->unparsed_uri;
1449 $url =~ s/update_email/prefs/;
1451 return $self->generic_redirect($url);
1454 return $self->generic_redirect;
1457 sub load_myopac_update_username {
1459 my $e = $self->editor;
1460 my $ctx = $self->ctx;
1461 my $username = $self->cgi->param('username') || '';
1462 my $current_pw = $self->cgi->param('current_pw') || '';
1464 $self->prepare_extended_user_info;
1466 my $allow_change = 1;
1468 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1469 if($lock_usernames == 1) {
1470 # Policy says no username changes
1473 # We want this further down.
1474 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1475 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1476 if($username_unlimit != 1) {
1478 # Default is "starts with a number"
1479 $regex_check = '^\d+';
1481 # You already have a username?
1482 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1487 if(!$allow_change) {
1488 my $url = $self->apache->unparsed_uri;
1489 $url =~ s/update_username/prefs/;
1491 return $self->generic_redirect($url);
1494 return Apache2::Const::OK
1495 unless $self->cgi->request_method eq 'POST';
1497 unless($username and $username !~ /\s/) { # any other username restrictions?
1498 $ctx->{invalid_username} = $username;
1499 return Apache2::Const::OK;
1502 # New username can't look like a barcode if we have a barcode regex
1503 if($regex_check and $username =~ /$regex_check/) {
1504 $ctx->{invalid_username} = $username;
1505 return Apache2::Const::OK;
1508 # New username has to look like a username if we have a username regex
1509 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1510 if($regex_check and $username !~ /$regex_check/) {
1511 $ctx->{invalid_username} = $username;
1512 return Apache2::Const::OK;
1515 if($username ne $e->requestor->usrname) {
1517 my $evt = $U->simplereq(
1519 'open-ils.actor.user.username.update',
1520 $e->authtoken, $username, $current_pw);
1522 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1523 $ctx->{password_incorrect} = 1;
1524 return Apache2::Const::OK;
1527 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1528 $ctx->{username_exists} = $username;
1529 return Apache2::Const::OK;
1533 my $url = $self->apache->unparsed_uri;
1534 $url =~ s/update_username/prefs/;
1536 return $self->generic_redirect($url);
1539 sub load_myopac_update_password {
1541 my $e = $self->editor;
1542 my $ctx = $self->ctx;
1544 return Apache2::Const::OK
1545 unless $self->cgi->request_method eq 'POST';
1547 my $current_pw = $self->cgi->param('current_pw') || '';
1548 my $new_pw = $self->cgi->param('new_pw') || '';
1549 my $new_pw2 = $self->cgi->param('new_pw2') || '';
1551 unless($new_pw eq $new_pw2) {
1552 $ctx->{password_nomatch} = 1;
1553 return Apache2::Const::OK;
1556 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1559 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1560 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1563 if($pw_regex and $new_pw !~ /$pw_regex/) {
1564 $ctx->{password_invalid} = 1;
1565 return Apache2::Const::OK;
1568 my $evt = $U->simplereq(
1570 'open-ils.actor.user.password.update',
1571 $e->authtoken, $new_pw, $current_pw);
1574 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1575 $ctx->{password_incorrect} = 1;
1576 return Apache2::Const::OK;
1579 my $url = $self->apache->unparsed_uri;
1580 $url =~ s/update_password/prefs/;
1582 return $self->generic_redirect($url);
1585 sub _update_bookbag_metadata {
1586 my ($self, $bookbag) = @_;
1588 $bookbag->name($self->cgi->param("name"));
1589 $bookbag->description($self->cgi->param("description"));
1591 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1595 sub load_myopac_bookbags {
1597 my $e = $self->editor;
1598 my $ctx = $self->ctx;
1600 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1601 $e->xact_begin; # replication...
1603 my $rv = $self->load_mylist;
1604 unless($rv eq Apache2::Const::OK) {
1609 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1611 {owner => $e->requestor->id, btype => 'bookbag'}, {
1612 order_by => {cbreb => 'name'},
1613 limit => $self->cgi->param('limit') || 10,
1614 offset => $self->cgi->param('offset') || 0
1620 if(!$ctx->{bookbags}) {
1622 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1625 # If the user wants a specific bookbag's items, load them.
1626 # XXX add bookbag item paging support
1628 if ($self->cgi->param("id")) {
1630 grep { $_->id eq $self->cgi->param("id") } @{$ctx->{bookbags}};
1634 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1637 if ($self->cgi->param("action") eq "editmeta") {
1638 if (!$self->_update_bookbag_metadata($bookbag)) {
1640 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1643 my $url = $self->ctx->{opac_root} . '/myopac/lists?id=' .
1646 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1647 if ($self->cgi->param($param)) {
1648 $url .= ";$param=" . uri_escape($self->cgi->param($param));
1652 return $self->generic_redirect($url);
1656 my $query = $self->_prepare_bookbag_container_query(
1657 $bookbag->id, $sorter, $modifier
1660 # XXX we need to limit the number of records per bbag; use third arg
1661 # of bib_container_items_via_search() i think.
1662 my $items = $U->bib_container_items_via_search($bookbag->id, $query)
1663 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1665 my (undef, @recs) = $self->get_records_and_facets(
1666 [ map {$_->target_biblio_record_entry->id} @$items ],
1671 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1673 $bookbag->items($items);
1677 return Apache2::Const::OK;
1681 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1682 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1683 sub load_myopac_bookbag_update {
1684 my ($self, $action, $list_id, @hold_recs) = @_;
1685 my $e = $self->editor;
1686 my $cgi = $self->cgi;
1688 # save_notes is effectively another action, but is passed in a separate
1689 # CGI parameter for what are really just layout reasons.
1690 $action = 'save_notes' if $cgi->param('save_notes');
1691 $action ||= $cgi->param('action');
1693 $list_id ||= $cgi->param('list');
1695 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1696 my @selected_item = $cgi->param('selected_item');
1697 my $shared = $cgi->param('shared');
1698 my $name = $cgi->param('name');
1699 my $description = $cgi->param('description');
1703 # This url intentionally leaves off the edit_notes parameter, but
1704 # may need to add some back in for paging.
1706 my $url = "https://" . $self->apache->hostname .
1707 $self->ctx->{opac_root} . "/myopac/lists?";
1709 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1710 if ($cgi->param($param)) {
1711 $url .= "$param=" . uri_escape($cgi->param($param)) . ";";
1715 if ($action eq 'create') {
1716 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1718 $list->description($description);
1719 $list->owner($e->requestor->id);
1720 $list->btype('bookbag');
1721 $list->pub($shared ? 't' : 'f');
1722 $success = $U->simplereq('open-ils.actor',
1723 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1725 } elsif($action eq 'place_hold') {
1727 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1728 unless (@hold_recs) {
1729 if (@selected_item) {
1730 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1731 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1735 return Apache2::Const::OK unless @hold_recs;
1736 $logger->info("placing holds from list page on: @hold_recs");
1738 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1739 $url .= ';hold_target=' . $_ for @hold_recs;
1740 foreach my $param (('loc', 'qtype', 'query')) {
1741 if ($cgi->param($param)) {
1742 $url .= ";$param=" . uri_escape($cgi->param($param));
1745 return $self->generic_redirect($url);
1749 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1751 return Apache2::Const::HTTP_BAD_REQUEST unless
1752 $list and $list->owner == $e->requestor->id;
1755 if($action eq 'delete') {
1756 $success = $U->simplereq('open-ils.actor',
1757 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1759 } elsif($action eq 'show') {
1760 unless($U->is_true($list->pub)) {
1762 $success = $U->simplereq('open-ils.actor',
1763 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1766 } elsif($action eq 'hide') {
1767 if($U->is_true($list->pub)) {
1769 $success = $U->simplereq('open-ils.actor',
1770 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1773 } elsif($action eq 'rename') {
1776 $success = $U->simplereq('open-ils.actor',
1777 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1780 } elsif($action eq 'add_rec') {
1781 foreach my $add_rec (@add_rec) {
1782 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1783 $item->bucket($list_id);
1784 $item->target_biblio_record_entry($add_rec);
1785 $success = $U->simplereq('open-ils.actor',
1786 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1787 last unless $success;
1790 } elsif($action eq 'del_item') {
1791 foreach (@selected_item) {
1792 $success = $U->simplereq(
1794 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1796 last unless $success;
1798 } elsif ($action eq 'save_notes') {
1799 $success = $self->update_bookbag_item_notes;
1800 $url .= "&id=" . uri_escape($cgi->param("id")) if $cgi->param("id");
1803 return $self->generic_redirect($url) if $success;
1805 # XXX FIXME Bucket failure doesn't have a page to show the user anything
1806 # right now. User just sees a 404 currently.
1808 $self->ctx->{bucket_action} = $action;
1809 $self->ctx->{bucket_action_failed} = 1;
1810 return Apache2::Const::OK;
1813 sub update_bookbag_item_notes {
1815 my $e = $self->editor;
1817 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
1818 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
1820 # We're going to leverage an API call that's already been written to check
1821 # permissions appropriately.
1823 my $a = create OpenSRF::AppSession("open-ils.actor");
1824 my $method = "open-ils.actor.container.item_note.cud";
1826 for my $note_key (@note_keys) {
1829 my $id = ($note_key =~ /(\d+)/)[0];
1832 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
1833 my $event = $e->die_event;
1834 $self->apache->log->warn(
1835 "error retrieving cbrebin id $id, got event " .
1839 $self->ctx->{bucket_action_event} = $event;
1843 if (length($self->cgi->param($note_key))) {
1844 $note->ischanged(1);
1845 $note->note($self->cgi->param($note_key));
1847 $note->isdeleted(1);
1850 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1852 if (defined $U->event_code($r)) {
1853 $self->apache->log->warn(
1854 "attempt to modify cbrebin " . $note->id .
1855 " returned event " . $r->{textcode}
1859 $self->ctx->{bucket_action_event} = $r;
1864 for my $item_key (@item_keys) {
1865 my $id = int(($item_key =~ /(\d+)/)[0]);
1866 my $text = $self->cgi->param($item_key);
1869 next unless length $text;
1871 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
1876 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1878 if (defined $U->event_code($r)) {
1879 $self->apache->log->warn(
1880 "attempt to create cbrebin for item " . $note->item .
1881 " returned event " . $r->{textcode}
1885 $self->ctx->{bucket_action_event} = $r;
1894 sub load_myopac_bookbag_print {
1897 $self->apache->content_type("text/plain; encoding=utf8");
1899 my $id = int($self->cgi->param("list"));
1901 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1904 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
1908 # Get the bookbag object itself, assuming we're allowed to.
1909 if ($self->editor->allowed("VIEW_CONTAINER")) {
1911 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1913 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
1917 "owner" => $self->editor->requestor->id,
1921 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1923 $bbag = pop @$bookbags;
1926 # If we have a bookbag we're allowed to look at, issue the A/T event
1927 # to get CSV, passing as a user param that search query we built before.
1929 $self->ctx->{csv} = $U->fire_object_event(
1930 undef, "container.biblio_record_entry_bucket.csv",
1931 $bbag, $self->editor->requestor->home_ou,
1932 undef, {"item_search" => $item_search}
1936 # Create a reasonable filename and set the content disposition to
1937 # provoke browser download dialogs.
1938 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
1940 $self->apache->headers_out->add(
1941 "Content-Disposition",
1942 "attachment;filename=$filename.csv"
1945 return Apache2::Const::OK;
1948 sub load_password_reset {
1950 my $cgi = $self->cgi;
1951 my $ctx = $self->ctx;
1952 my $barcode = $cgi->param('barcode');
1953 my $username = $cgi->param('username');
1954 my $email = $cgi->param('email');
1955 my $pwd1 = $cgi->param('pwd1');
1956 my $pwd2 = $cgi->param('pwd2');
1957 my $uuid = $ctx->{page_args}->[0];
1961 $logger->info("patron password reset with uuid $uuid");
1963 if ($pwd1 and $pwd2) {
1965 if ($pwd1 eq $pwd2) {
1967 my $response = $U->simplereq(
1969 'open-ils.actor.patron.password_reset.commit',
1972 $logger->info("patron password reset response " . Dumper($response));
1974 if ($U->event_code($response)) { # non-success event
1976 my $code = $response->{textcode};
1978 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
1979 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
1982 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
1983 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
1988 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
1991 } else { # passwords not equal
1993 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
1996 } else { # 2 password values needed
1998 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2001 } elsif ($barcode or $username) {
2003 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2004 push(@params, $email) if $email;
2008 'open-ils.actor.patron.password_reset.request', @params);
2010 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2013 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2014 return Apache2::Const::OK;