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;
180 my $stat = $self->_load_user_with_prefs;
181 return $stat if $stat;
183 my $user_prefs = $self->fetch_optin_prefs;
184 $user_prefs = $self->update_optin_prefs($user_prefs)
185 if $self->cgi->request_method eq 'POST';
187 $self->ctx->{opt_in_settings} = $user_prefs;
189 return Apache2::Const::OK
190 unless $self->cgi->request_method eq 'POST';
193 my $set_map = $self->ctx->{user_setting_map};
197 opac.default_sms_notify
199 my $val = $self->cgi->param($key);
200 $settings{$key}= $val unless $$set_map{$key} eq $val;
203 my $key = 'opac.default_sms_carrier';
204 my $val = $self->cgi->param('sms_carrier');
205 $settings{$key}= $val unless $$set_map{$key} eq $val;
207 $key = 'opac.hold_notify';
208 my @notify_methods = ();
209 if ($self->cgi->param($key . ".email") eq 'on') {
210 push @notify_methods, "email";
212 if ($self->cgi->param($key . ".phone") eq 'on') {
213 push @notify_methods, "phone";
215 if ($self->cgi->param($key . ".sms") eq 'on') {
216 push @notify_methods, "sms";
218 $val = join("|",@notify_methods);
219 $settings{$key}= $val unless $$set_map{$key} eq $val;
221 # Send the modified settings off to be saved
224 'open-ils.actor.patron.settings.update',
225 $self->editor->authtoken, undef, \%settings);
227 # re-fetch user prefs
228 $self->ctx->{updated_user_settings} = \%settings;
229 return $self->_load_user_with_prefs || Apache2::Const::OK;
232 sub fetch_optin_prefs {
234 my $e = $self->editor;
236 # fetch all of the opt-in settings the user has access to
237 # XXX: user's should in theory have options to opt-in to notices
238 # for remote locations, but that opens the door for a large
239 # set of generally un-used opt-ins.. needs discussion
240 my $opt_ins = $U->simplereq(
242 'open-ils.actor.event_def.opt_in.settings.atomic',
243 $e->authtoken, $e->requestor->home_ou);
245 # some opt-ins are staff-only
246 $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
248 # fetch user setting values for each of the opt-in settings
249 my $user_set = $U->simplereq(
251 'open-ils.actor.patron.settings.retrieve',
254 [map {$_->name} @$opt_ins]
257 return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
260 sub update_optin_prefs {
262 my $user_prefs = shift;
263 my $e = $self->editor;
264 my @settings = $self->cgi->param('setting');
267 # apply now-true settings
268 for my $applied (@settings) {
269 # see if setting is already applied to this user
270 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
271 $newsets{$applied} = OpenSRF::Utils::JSON->true;
274 # remove now-false settings
275 for my $pref (grep { $_->{value} } @$user_prefs) {
276 $newsets{$pref->{cust}->name} = undef
277 unless grep { $_ eq $pref->{cust}->name } @settings;
282 'open-ils.actor.patron.settings.update',
283 $e->authtoken, $e->requestor->id, \%newsets);
285 # update the local prefs to match reality
286 for my $pref (@$user_prefs) {
287 $pref->{value} = $newsets{$pref->{cust}->name}
288 if exists $newsets{$pref->{cust}->name};
294 sub _load_user_with_prefs {
296 my $stat = $self->prepare_extended_user_info('settings');
297 return $stat if $stat; # not-OK
299 $self->ctx->{user_setting_map} = {
300 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
301 @{$self->ctx->{user}->settings}
307 sub _get_bookbag_sort_params {
308 my ($self, $param_name) = @_;
310 # The interface that feeds this cgi parameter will provide a single
311 # argument for a QP sort filter, and potentially a modifier after a period.
312 # In practice this means the "sort" parameter will be something like
313 # "titlesort" or "authorsort.descending".
314 my $sorter = $self->cgi->param($param_name) || "";
317 $sorter =~ s/^(.*?)\.(.*)/$1/;
318 $modifier = $2 || undef;
321 return ($sorter, $modifier);
324 sub _prepare_bookbag_container_query {
325 my ($self, $container_id, $sorter, $modifier) = @_;
328 "container(bre,bookbag,%d,%s)%s%s",
329 $container_id, $self->editor->authtoken,
330 ($sorter ? " sort($sorter)" : ""),
331 ($modifier ? "#$modifier" : "")
335 sub _prepare_anonlist_sorting_query {
336 my ($self, $list, $sorter, $modifier) = @_;
339 "record_list(%s)%s%s",
341 ($sorter ? " sort($sorter)" : ""),
342 ($modifier ? "#$modifier" : "")
347 sub load_myopac_prefs_settings {
352 opac.default_search_location
353 opac.default_pickup_location
356 my $stat = $self->_load_user_with_prefs;
357 return $stat if $stat;
359 return Apache2::Const::OK
360 unless $self->cgi->request_method eq 'POST';
362 # some setting values from the form don't match the
363 # required value/format for the db, so they have to be
364 # individually translated.
367 my $set_map = $self->ctx->{user_setting_map};
369 foreach my $key (@user_prefs) {
370 my $val = $self->cgi->param($key);
371 $settings{$key}= $val unless $$set_map{$key} eq $val;
374 my $now = DateTime->now->strftime('%F');
375 foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
376 my $val = $self->cgi->param($key);
377 if($val and $val eq 'on') {
378 # Set the start time to 'now' unless a start time already exists for the user
379 $settings{$key} = $now unless $$set_map{$key};
381 # clear the start time if one previously existed for the user
382 $settings{$key} = undef if $$set_map{$key};
386 # Send the modified settings off to be saved
389 'open-ils.actor.patron.settings.update',
390 $self->editor->authtoken, undef, \%settings);
392 # re-fetch user prefs
393 $self->ctx->{updated_user_settings} = \%settings;
394 return $self->_load_user_with_prefs || Apache2::Const::OK;
397 sub fetch_user_holds {
399 my $hold_ids = shift;
400 my $ids_only = shift;
402 my $available = shift;
406 my $e = $self->editor;
409 my $circ = OpenSRF::AppSession->create('open-ils.circ');
411 $hold_ids = $circ->request(
412 'open-ils.circ.holds.id_list.retrieve.authoritative',
418 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
422 return $hold_ids if $ids_only or @$hold_ids == 0;
425 suppress_notices => 1,
426 suppress_transits => 1,
428 suppress_patron_details => 1
431 # ----------------------------------------------------------------
432 # Collect holds in batches of $batch_size for faster retrieval
436 my $mk_req_batch = sub {
438 my $top_idx = $batch_idx + $batch_size;
439 while($batch_idx < $top_idx) {
440 my $hold_id = $hold_ids->[$batch_idx++];
441 last unless $hold_id;
442 my $ses = OpenSRF::AppSession->create('open-ils.circ');
443 my $req = $ses->request(
444 'open-ils.circ.hold.details.retrieve',
445 $e->authtoken, $hold_id, $args);
446 push(@ses, {ses => $ses, req => $req});
452 my(@collected, @holds, @ses);
455 @ses = $mk_req_batch->() if $first;
456 last if $first and not @ses;
459 # If desired by the caller, filter any holds that are not available.
461 @collected = grep { $_->{hold}->{status} == 4 } @collected;
463 while(my $blob = pop(@collected)) {
464 my (undef, @data) = $self->get_records_and_facets(
465 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
467 $blob->{marc_xml} = $data[0]->{marc_xml};
472 for my $req_data (@ses) {
473 push(@collected, {hold => $req_data->{req}->gather(1)});
474 $req_data->{ses}->kill_me;
477 @ses = $mk_req_batch->();
478 last unless @collected or @ses;
482 # put the holds back into the original server sort order
484 for my $id (@$hold_ids) {
485 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
491 sub handle_hold_update {
494 my $hold_ids = shift;
495 my $e = $self->editor;
498 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
499 @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
501 my $circ = OpenSRF::AppSession->create('open-ils.circ');
503 if($action =~ /cancel/) {
505 for my $hold_id (@hold_ids) {
506 my $resp = $circ->request(
507 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
510 } elsif ($action =~ /activate|suspend/) {
513 for my $hold_id (@hold_ids) {
514 my $vals = {id => $hold_id};
516 if($action =~ /activate/) {
517 $vals->{frozen} = 'f';
518 $vals->{thaw_date} = undef;
520 } elsif($action =~ /suspend/) {
521 $vals->{frozen} = 't';
522 # $vals->{thaw_date} = TODO;
524 push(@$vlist, $vals);
527 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
528 $self->ctx->{hold_suspend_post_capture} = 1 if
529 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
531 } elsif ($action eq 'edit') {
534 my $val = {"id" => $_};
535 $val->{"frozen"} = $self->cgi->param("frozen");
536 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
538 for my $field (qw/expire_time thaw_date/) {
539 # XXX TODO make this support other date formats, not just
541 next unless $self->cgi->param($field) =~
542 m:^(\d{2})/(\d{2})/(\d{4})$:;
543 $val->{$field} = "$3-$1-$2";
549 'open-ils.circ.hold.update.batch.atomic',
550 $e->authtoken, undef, \@vals
551 )->gather(1); # LFW XXX test for failure
552 $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
553 foreach my $param (('loc', 'qtype', 'query')) {
554 if ($self->cgi->param($param)) {
555 $url .= ";$param=" . uri_escape($self->cgi->param($param));
561 return defined($url) ? $self->generic_redirect($url) : undef;
564 sub load_myopac_holds {
566 my $e = $self->editor;
567 my $ctx = $self->ctx;
569 my $limit = $self->cgi->param('limit') || 0;
570 my $offset = $self->cgi->param('offset') || 0;
571 my $action = $self->cgi->param('action') || '';
572 my $hold_id = $self->cgi->param('id');
573 my $available = int($self->cgi->param('available') || 0);
575 my $hold_handle_result;
576 $hold_handle_result = $self->handle_hold_update($action) if $action;
578 $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
580 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
585 sub load_place_hold {
587 my $ctx = $self->ctx;
588 my $gos = $ctx->{get_org_setting};
589 my $e = $self->editor;
590 my $cgi = $self->cgi;
592 $self->ctx->{page} = 'place_hold';
593 my @targets = $cgi->param('hold_target');
594 my @parts = $cgi->param('part');
596 $ctx->{hold_type} = $cgi->param('hold_type');
597 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
598 $ctx->{email_notify} = $cgi->param('email_notify');
599 if ($cgi->param('phone_notify_checkbox')) {
600 $ctx->{phone_notify} = $cgi->param('phone_notify');
602 if ($cgi->param('sms_notify_checkbox')) {
603 $ctx->{sms_notify} = $cgi->param('sms_notify');
604 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
607 return $self->generic_redirect unless @targets;
609 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
611 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
616 au => ['settings', 'card']
619 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
620 my $user_setting_map = {
621 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
623 $ctx->{staff_recipient}->settings
626 $ctx->{user_setting_map} = $user_setting_map;
628 my $default_notify = $$user_setting_map{'opac.hold_notify'} || '';
629 if ($default_notify =~ /email/) {
630 $ctx->{default_email_notify} = 'checked';
632 $ctx->{default_email_notify} = '';
634 if ($default_notify =~ /phone/) {
635 $ctx->{default_phone_notify} = 'checked';
637 $ctx->{default_phone_notify} = '';
639 if ($default_notify =~ /sms/) {
640 $ctx->{default_sms_notify} = 'checked';
642 $ctx->{default_sms_notify} = '';
645 # If we have a default pickup location, grab it
646 if ($$user_setting_map{'opac.default_pickup_location'}) {
647 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
650 my $request_lib = $e->requestor->ws_ou;
652 $ctx->{hold_data} = \@hold_data;
656 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
657 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
658 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
659 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
663 my $type_dispatch = {
665 my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
667 for my $id (@targets) { # force back into the correct order
668 my ($rec) = grep {$_->id eq $id} @$recs;
670 # NOTE: if tpac ever supports locked-down pickup libs,
671 # we'll need to pass a pickup_lib param along with the
672 # record to filter the set of monographic parts.
673 my $parts = $U->simplereq(
675 'open-ils.search.biblio.record_hold_parts',
679 # T holds on records that have parts are OK, but if the record has
680 # no non-part copies, the hold will ultimately fail. When that
681 # happens, require the user to select a part.
682 my $part_required = 0;
684 my $np_copies = $e->json_query({
685 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
686 from => {acp => {acn => {}, acpm => {type => 'left'}}},
688 '+acp' => {deleted => 'f'},
689 '+acn' => {deleted => 'f', record => $rec->id},
690 '+acpm' => {id => undef}
693 $part_required = 1 if $np_copies->[0]->{count} == 0;
696 push(@hold_data, $data_filler->({
700 part_required => $part_required
705 my $vols = $e->batch_retrieve_asset_call_number([
708 "flesh_fields" => {"acn" => ["record"]}
710 ], {substream => 1});
712 for my $id (@targets) {
713 my ($vol) = grep {$_->id eq $id} @$vols;
714 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
718 my $copies = $e->batch_retrieve_asset_copy([
723 "acp" => ["call_number"]
726 ], {substream => 1});
728 for my $id (@targets) {
729 my ($copy) = grep {$_->id eq $id} @$copies;
730 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
734 my $isses = $e->batch_retrieve_serial_issuance([
738 "siss" => ["subscription"], "ssub" => ["record_entry"]
741 ], {substream => 1});
743 for my $id (@targets) {
744 my ($iss) = grep {$_->id eq $id} @$isses;
745 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
750 }->{$ctx->{hold_type}}->();
752 # caller sent bad target IDs or the wrong hold type
753 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
755 # generate the MARC xml for each record
756 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
758 my $pickup_lib = $cgi->param('pickup_lib');
759 # no pickup lib means no holds placement
760 return Apache2::Const::OK unless $pickup_lib;
762 $ctx->{hold_attempt_made} = 1;
764 # Give the original CGI params back to the user in case they
765 # want to try to override something.
766 $ctx->{orig_params} = $cgi->Vars;
767 delete $ctx->{orig_params}{submit};
768 delete $ctx->{orig_params}{hold_target};
769 delete $ctx->{orig_params}{part};
771 my $usr = $e->requestor->id;
773 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
774 # find the real hold target
776 $usr = $U->simplereq(
778 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
779 $e->authtoken, $cgi->param("hold_usr"));
781 if (defined $U->event_code($usr)) {
782 $ctx->{hold_failed} = 1;
783 $ctx->{hold_failed_event} = $usr;
787 # target_id is the true target_id for holds placement.
788 # needed for attempt_hold_placement()
789 # With the exception of P-type holds, target_id == target->id.
790 $_->{target_id} = $_->{target}->id for @hold_data;
792 if ($ctx->{hold_type} eq 'T') {
794 # Much like quantum wave-particles, P-type holds pop into
795 # and out of existence at the user's whim. For our purposes,
796 # we treat such holds as T(itle) holds with a selected_part
797 # designation. When the time comes to pass the hold information
798 # off for holds possibility testing and placement, make it look
799 # like a real P-type hold.
800 my (@p_holds, @t_holds);
802 for my $idx (0..$#parts) {
803 my $hdata = $hold_data[$idx];
804 if (my $part = $parts[$idx]) {
805 $hdata->{target_id} = $part;
806 $hdata->{selected_part} = $part;
807 push(@p_holds, $hdata);
809 push(@t_holds, $hdata);
813 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
814 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
817 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
820 # NOTE: we are leaving the staff-placed patron barcode cookie
821 # in place. Otherwise, it's not possible to place more than
822 # one hold for the patron within a staff/patron session. This
823 # does leave the barcode to linger longer than is ideal, but
824 # normal staff work flow will cause the cookie to be replaced
825 # with each new patron anyway.
826 # TODO: See about getting the staff client to clear the cookie
828 # return to the place_hold page so the results of the hold
829 # placement attempt can be reported to the user
830 return Apache2::Const::OK;
833 sub attempt_hold_placement {
834 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
835 my $cgi = $self->cgi;
836 my $ctx = $self->ctx;
837 my $e = $self->editor;
839 # First see if we should warn/block for any holds that
840 # might have locally available items.
841 for my $hdata (@hold_data) {
842 my ($local_block, $local_alert) = $self->local_avail_concern(
843 $hdata->{target_id}, $hold_type, $pickup_lib);
846 $hdata->{hold_failed} = 1;
847 $hdata->{hold_local_block} = 1;
848 } elsif ($local_alert) {
849 $hdata->{hold_failed} = 1;
850 $hdata->{hold_local_alert} = 1;
854 my $method = 'open-ils.circ.holds.test_and_create.batch';
855 $method .= '.override' if $cgi->param('override');
857 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
859 if(@create_targets) {
861 my $bses = OpenSRF::AppSession->create('open-ils.circ');
862 my $breq = $bses->request(
865 $data_filler->({ patronid => $usr,
866 pickup_lib => $pickup_lib,
867 hold_type => $hold_type
872 while (my $resp = $breq->recv) {
874 $resp = $resp->content;
875 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
877 if ($U->event_code($resp)) {
878 $ctx->{general_hold_error} = $resp;
882 my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
883 my $result = $resp->{result};
885 if ($U->event_code($result)) {
886 # e.g. permission denied
887 $hdata->{hold_failed} = 1;
888 $hdata->{hold_failed_event} = $result;
892 if(not ref $result and $result > 0) {
893 # successul hold returns the hold ID
895 $hdata->{hold_success} = $result;
898 # hold-specific failure event
899 $hdata->{hold_failed} = 1;
901 if (ref $result eq 'HASH') {
902 $hdata->{hold_failed_event} = $result->{last_event};
904 if ($result->{age_protected_copy}) {
905 $hdata->{could_override} = 1;
906 $hdata->{age_protect} = 1;
908 $hdata->{could_override} = $result->{place_unfillable};
910 } elsif (ref $result eq 'ARRAY') {
911 $hdata->{hold_failed_event} = $result->[0];
913 if ($result->[3]) { # age_protect_only
914 $hdata->{could_override} = 1;
915 $hdata->{age_protect} = 1;
917 $hdata->{could_override} = $result->[4]; # place_unfillable
928 sub fetch_user_circs {
930 my $flesh = shift; # flesh bib data, etc.
931 my $circ_ids = shift;
935 my $e = $self->editor;
940 @circ_ids = @$circ_ids;
945 select => {circ => ['id']},
949 usr => $e->requestor->id,
950 checkin_time => undef,
952 {stop_fines => undef},
953 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
957 order_by => {circ => ['due_date']}
960 $query->{limit} = $limit if $limit;
961 $query->{offset} = $offset if $offset;
963 my $ids = $e->json_query($query);
964 @circ_ids = map {$_->{id}} @$ids;
967 return [] unless @circ_ids;
972 circ => ['target_copy'],
973 acp => ['call_number'],
979 my $circs = $e->search_action_circulation(
980 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
983 for my $circ (@$circs) {
986 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
987 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
988 undef # pre-cat copy, use the dummy title/author instead
993 # make sure the final list is in the correct order
995 for my $id (@circ_ids) {
998 (grep { $_->{circ}->id == $id } @circs)
1002 return \@sorted_circs;
1006 sub handle_circ_renew {
1009 my $ctx = $self->ctx;
1011 my @renew_ids = $self->cgi->param('circ');
1013 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1015 # TODO: fire off renewal calls in batches to speed things up
1017 for my $circ (@$circs) {
1019 my $evt = $U->simplereq(
1021 'open-ils.circ.renew',
1022 $self->editor->authtoken,
1024 patron_id => $self->editor->requestor->id,
1025 copy_id => $circ->{circ}->target_copy,
1030 # TODO return these, then insert them into the circ data
1031 # blob that is shoved into the template for each circ
1032 # so the template won't have to match them
1033 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1040 sub load_myopac_circs {
1042 my $e = $self->editor;
1043 my $ctx = $self->ctx;
1046 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1047 my $offset = $self->cgi->param('offset') || 0;
1048 my $action = $self->cgi->param('action') || '';
1050 # perform the renewal first if necessary
1051 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1053 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1055 my $success_renewals = 0;
1056 my $failed_renewals = 0;
1057 for my $data (@{$ctx->{circs}}) {
1058 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1061 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1062 $data->{renewal_response} = $evt;
1063 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1064 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1068 $ctx->{success_renewals} = $success_renewals;
1069 $ctx->{failed_renewals} = $failed_renewals;
1071 return Apache2::Const::OK;
1074 sub load_myopac_circ_history {
1076 my $e = $self->editor;
1077 my $ctx = $self->ctx;
1078 my $limit = $self->cgi->param('limit') || 15;
1079 my $offset = $self->cgi->param('offset') || 0;
1081 $ctx->{circ_history_limit} = $limit;
1082 $ctx->{circ_history_offset} = $offset;
1084 my $circ_ids = $e->json_query({
1088 transform => 'action.usr_visible_circs',
1089 result_field => 'id'
1093 where => {id => $e->requestor->id},
1098 $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1099 return Apache2::Const::OK;
1102 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1103 sub load_myopac_hold_history {
1105 my $e = $self->editor;
1106 my $ctx = $self->ctx;
1107 my $limit = $self->cgi->param('limit') || 15;
1108 my $offset = $self->cgi->param('offset') || 0;
1109 $ctx->{hold_history_limit} = $limit;
1110 $ctx->{hold_history_offset} = $offset;
1112 my $hold_ids = $e->json_query({
1116 transform => 'action.usr_visible_holds',
1117 result_field => 'id'
1121 where => {id => $e->requestor->id},
1126 $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
1127 return Apache2::Const::OK;
1130 sub load_myopac_payment_form {
1134 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1135 $r = $self->prepare_extended_user_info and return $r;
1137 return Apache2::Const::OK;
1140 # TODO: add other filter options as params/configs/etc.
1141 sub load_myopac_payments {
1143 my $limit = $self->cgi->param('limit') || 20;
1144 my $offset = $self->cgi->param('offset') || 0;
1145 my $e = $self->editor;
1147 $self->ctx->{payment_history_limit} = $limit;
1148 $self->ctx->{payment_history_offset} = $offset;
1151 $args->{limit} = $limit if $limit;
1152 $args->{offset} = $offset if $offset;
1154 if (my $max_age = $self->ctx->{get_org_setting}->(
1155 $e->requestor->home_ou, "opac.payment_history_age_limit"
1157 my $min_ts = DateTime->now(
1158 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1159 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1161 $logger->info("XXX min_ts: $min_ts");
1162 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1165 $self->ctx->{payments} = $U->simplereq(
1167 'open-ils.actor.user.payments.retrieve.atomic',
1168 $e->authtoken, $e->requestor->id, $args);
1170 return Apache2::Const::OK;
1173 # 1. caches the form parameters
1174 # 2. loads the credit card payment "Processing..." page
1175 sub load_myopac_pay_init {
1177 my $cache = OpenSRF::Utils::Cache->new('global');
1179 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1181 if (!@payment_xacts) {
1182 # for consistency with load_myopac_payment_form() and
1183 # to preserve backwards compatibility, if no xacts are
1184 # selected, assume all (applicable) transactions are wanted.
1185 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1186 return $stat if $stat;
1188 map { $_->{xact}->id } (
1189 @{$self->ctx->{fines}->{circulation}},
1190 @{$self->ctx->{fines}->{grocery}}
1194 return $self->generic_redirect unless @payment_xacts;
1196 my $cc_args = {"where_process" => 1};
1198 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1199 number cvv2 expire_year expire_month billing_first
1200 billing_last billing_address billing_city billing_state
1205 cc_args => $cc_args,
1206 user => $self->ctx->{user}->id,
1207 xacts => \@payment_xacts
1210 # generate a temporary cache token and cache the form data
1211 my $token = md5_hex($$ . time() . rand());
1212 $cache->put_cache($token, $cache_args, 30);
1214 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1216 # after we render the processing page, we quickly redirect to submit
1217 # the actual payment. The refresh url contains the payment token.
1218 # It also contains the list of xact IDs, which allows us to clear the
1219 # cache at the earliest possible time while leaving a trace of which
1220 # transactions we were processing, so the UI can bring the user back
1221 # to the payment form w/ the same xacts if the payment fails.
1223 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1224 $refresh .= ";xact=$_" for @payment_xacts;
1225 $self->ctx->{refresh} = $refresh;
1227 return Apache2::Const::OK;
1230 # retrieve the cached CC payment info and send off for processing
1231 sub load_myopac_pay {
1233 my $token = $self->ctx->{page_args}->[0];
1234 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1236 my $cache = OpenSRF::Utils::Cache->new('global');
1237 my $cache_args = $cache->get_cache($token);
1238 $cache->delete_cache($token);
1240 # this page is loaded immediately after the token is created.
1241 # if the cached data is not there, it's because of an invalid
1242 # token (or cache failure) and not because of a timeout.
1243 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1245 my @payment_xacts = @{$cache_args->{xacts}};
1246 my $cc_args = $cache_args->{cc_args};
1248 # as an added security check, verify the user submitting
1249 # the form is the same as the user whose data was cached
1250 return Apache2::Const::HTTP_BAD_REQUEST unless
1251 $cache_args->{user} == $self->ctx->{user}->id;
1253 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1256 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1258 # balance_owed is computed specifically from the fines we're paying
1259 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1260 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1261 return Apache2::Const::HTTP_BAD_REQUEST;
1265 "cc_args" => $cc_args,
1266 "userid" => $self->ctx->{user}->id,
1267 "payment_type" => "credit_card_payment",
1268 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1271 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1272 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1275 $self->ctx->{"payment_response"} = $resp;
1277 unless ($resp->{"textcode"}) {
1278 $self->ctx->{printable_receipt} = $U->simplereq(
1279 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1280 $self->editor->authtoken, $resp->{payments}
1284 return Apache2::Const::OK;
1287 sub load_myopac_receipt_print {
1290 $self->ctx->{printable_receipt} = $U->simplereq(
1291 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1292 $self->editor->authtoken, [$self->cgi->param("payment")]
1295 return Apache2::Const::OK;
1298 sub load_myopac_receipt_email {
1301 # The following ML method doesn't actually check whether the user in
1302 # question has an email address, so we do.
1303 if ($self->ctx->{user}->email) {
1304 $self->ctx->{email_receipt_result} = $U->simplereq(
1305 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1306 $self->editor->authtoken, [$self->cgi->param("payment")]
1309 $self->ctx->{email_receipt_result} =
1310 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1313 return Apache2::Const::OK;
1317 my ($self, $limit, $offset, $id_list) = @_;
1319 # XXX TODO: check for failure after various network calls
1321 # It may be unclear, but this result structure lumps circulation and
1322 # reservation fines together, and keeps grocery fines separate.
1323 $self->ctx->{"fines"} = {
1324 "circulation" => [],
1331 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1333 # TODO: This should really be a ML call, but the existing calls
1334 # return an excessive amount of data and don't offer streaming
1336 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1338 my $req = $cstore->request(
1339 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1341 usr => $self->editor->requestor->id,
1342 balance_owed => {'!=' => 0},
1343 ($id_list && @$id_list ? ("id" => $id_list) : ()),
1348 mobts => [qw/grocery circulation reservation/],
1349 bresv => ['target_resource_type'],
1353 circ => ['target_copy'],
1354 acp => ['call_number'],
1357 order_by => { mobts => 'xact_start' },
1362 my @total_keys = qw/total_paid total_owed balance_owed/;
1363 $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1365 while(my $resp = $req->recv) {
1366 my $mobts = $resp->content;
1367 my $circ = $mobts->circulation;
1370 if($mobts->grocery) {
1371 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1372 $last_billing = pop(@billings);
1375 # XXX TODO confirm that the following, and the later division by 100.0
1376 # to get a floating point representation once again, is sufficiently
1377 # "money-safe" math.
1378 $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1380 my $marc_xml = undef;
1381 if ($mobts->xact_type eq 'reservation' and
1382 $mobts->reservation->target_resource_type->record) {
1383 $marc_xml = XML::LibXML->new->parse_string(
1384 $mobts->reservation->target_resource_type->record->marc
1386 } elsif ($mobts->xact_type eq 'circulation' and
1387 $circ->target_copy->call_number->id != -1) {
1388 $marc_xml = XML::LibXML->new->parse_string(
1389 $circ->target_copy->call_number->record->marc
1394 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1397 last_grocery_billing => $last_billing,
1398 marc_xml => $marc_xml
1405 $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1409 sub prepare_fines_for_payment {
1410 # This assumes $self->prepare_fines has already been run
1414 if ($self->ctx->{fines}) {
1415 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1416 @{$self->ctx->{fines}->{circulation}},
1417 @{$self->ctx->{fines}->{grocery}}
1424 sub load_myopac_main {
1426 my $limit = $self->cgi->param('limit') || 0;
1427 my $offset = $self->cgi->param('offset') || 0;
1428 $self->ctx->{search_ou} = $self->_get_search_lib();
1430 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1433 sub load_myopac_update_email {
1435 my $e = $self->editor;
1436 my $ctx = $self->ctx;
1437 my $email = $self->cgi->param('email') || '';
1438 my $current_pw = $self->cgi->param('current_pw') || '';
1440 # needed for most up-to-date email address
1441 if (my $r = $self->prepare_extended_user_info) { return $r };
1443 return Apache2::Const::OK
1444 unless $self->cgi->request_method eq 'POST';
1446 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1447 $ctx->{invalid_email} = $email;
1448 return Apache2::Const::OK;
1451 my $stat = $U->simplereq(
1453 'open-ils.actor.user.email.update',
1454 $e->authtoken, $email, $current_pw);
1456 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1457 $ctx->{password_incorrect} = 1;
1458 return Apache2::Const::OK;
1461 unless ($self->cgi->param("redirect_to")) {
1462 my $url = $self->apache->unparsed_uri;
1463 $url =~ s/update_email/prefs/;
1465 return $self->generic_redirect($url);
1468 return $self->generic_redirect;
1471 sub load_myopac_update_username {
1473 my $e = $self->editor;
1474 my $ctx = $self->ctx;
1475 my $username = $self->cgi->param('username') || '';
1476 my $current_pw = $self->cgi->param('current_pw') || '';
1478 $self->prepare_extended_user_info;
1480 my $allow_change = 1;
1482 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1483 if($lock_usernames == 1) {
1484 # Policy says no username changes
1487 # We want this further down.
1488 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1489 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1490 if($username_unlimit != 1) {
1492 # Default is "starts with a number"
1493 $regex_check = '^\d+';
1495 # You already have a username?
1496 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1501 if(!$allow_change) {
1502 my $url = $self->apache->unparsed_uri;
1503 $url =~ s/update_username/prefs/;
1505 return $self->generic_redirect($url);
1508 return Apache2::Const::OK
1509 unless $self->cgi->request_method eq 'POST';
1511 unless($username and $username !~ /\s/) { # any other username restrictions?
1512 $ctx->{invalid_username} = $username;
1513 return Apache2::Const::OK;
1516 # New username can't look like a barcode if we have a barcode regex
1517 if($regex_check and $username =~ /$regex_check/) {
1518 $ctx->{invalid_username} = $username;
1519 return Apache2::Const::OK;
1522 # New username has to look like a username if we have a username regex
1523 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1524 if($regex_check and $username !~ /$regex_check/) {
1525 $ctx->{invalid_username} = $username;
1526 return Apache2::Const::OK;
1529 if($username ne $e->requestor->usrname) {
1531 my $evt = $U->simplereq(
1533 'open-ils.actor.user.username.update',
1534 $e->authtoken, $username, $current_pw);
1536 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1537 $ctx->{password_incorrect} = 1;
1538 return Apache2::Const::OK;
1541 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1542 $ctx->{username_exists} = $username;
1543 return Apache2::Const::OK;
1547 my $url = $self->apache->unparsed_uri;
1548 $url =~ s/update_username/prefs/;
1550 return $self->generic_redirect($url);
1553 sub load_myopac_update_password {
1555 my $e = $self->editor;
1556 my $ctx = $self->ctx;
1558 return Apache2::Const::OK
1559 unless $self->cgi->request_method eq 'POST';
1561 my $current_pw = $self->cgi->param('current_pw') || '';
1562 my $new_pw = $self->cgi->param('new_pw') || '';
1563 my $new_pw2 = $self->cgi->param('new_pw2') || '';
1565 unless($new_pw eq $new_pw2) {
1566 $ctx->{password_nomatch} = 1;
1567 return Apache2::Const::OK;
1570 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1573 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1574 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1577 if($pw_regex and $new_pw !~ /$pw_regex/) {
1578 $ctx->{password_invalid} = 1;
1579 return Apache2::Const::OK;
1582 my $evt = $U->simplereq(
1584 'open-ils.actor.user.password.update',
1585 $e->authtoken, $new_pw, $current_pw);
1588 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1589 $ctx->{password_incorrect} = 1;
1590 return Apache2::Const::OK;
1593 my $url = $self->apache->unparsed_uri;
1594 $url =~ s/update_password/prefs/;
1596 return $self->generic_redirect($url);
1599 sub _update_bookbag_metadata {
1600 my ($self, $bookbag) = @_;
1602 $bookbag->name($self->cgi->param("name"));
1603 $bookbag->description($self->cgi->param("description"));
1605 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1609 sub load_myopac_bookbags {
1611 my $e = $self->editor;
1612 my $ctx = $self->ctx;
1614 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1615 $e->xact_begin; # replication...
1617 my $rv = $self->load_mylist;
1618 unless($rv eq Apache2::Const::OK) {
1623 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1625 {owner => $e->requestor->id, btype => 'bookbag'}, {
1626 order_by => {cbreb => 'name'},
1627 limit => $self->cgi->param('limit') || 10,
1628 offset => $self->cgi->param('offset') || 0
1634 if(!$ctx->{bookbags}) {
1636 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1639 # If the user wants a specific bookbag's items, load them.
1640 # XXX add bookbag item paging support
1642 if ($self->cgi->param("id")) {
1644 grep { $_->id eq $self->cgi->param("id") } @{$ctx->{bookbags}};
1648 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1651 if ($self->cgi->param("action") eq "editmeta") {
1652 if (!$self->_update_bookbag_metadata($bookbag)) {
1654 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1657 my $url = $self->ctx->{opac_root} . '/myopac/lists?id=' .
1660 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1661 if ($self->cgi->param($param)) {
1662 $url .= ";$param=" . uri_escape($self->cgi->param($param));
1666 return $self->generic_redirect($url);
1670 my $query = $self->_prepare_bookbag_container_query(
1671 $bookbag->id, $sorter, $modifier
1674 # XXX we need to limit the number of records per bbag; use third arg
1675 # of bib_container_items_via_search() i think.
1676 my $items = $U->bib_container_items_via_search($bookbag->id, $query)
1677 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1679 my (undef, @recs) = $self->get_records_and_facets(
1680 [ map {$_->target_biblio_record_entry->id} @$items ],
1685 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1687 $bookbag->items($items);
1691 return Apache2::Const::OK;
1695 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1696 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1697 sub load_myopac_bookbag_update {
1698 my ($self, $action, $list_id, @hold_recs) = @_;
1699 my $e = $self->editor;
1700 my $cgi = $self->cgi;
1702 # save_notes is effectively another action, but is passed in a separate
1703 # CGI parameter for what are really just layout reasons.
1704 $action = 'save_notes' if $cgi->param('save_notes');
1705 $action ||= $cgi->param('action');
1707 $list_id ||= $cgi->param('list');
1709 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1710 my @selected_item = $cgi->param('selected_item');
1711 my $shared = $cgi->param('shared');
1712 my $name = $cgi->param('name');
1713 my $description = $cgi->param('description');
1717 # This url intentionally leaves off the edit_notes parameter, but
1718 # may need to add some back in for paging.
1720 my $url = "https://" . $self->apache->hostname .
1721 $self->ctx->{opac_root} . "/myopac/lists?";
1723 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1724 if ($cgi->param($param)) {
1725 $url .= "$param=" . uri_escape($cgi->param($param)) . ";";
1729 if ($action eq 'create') {
1730 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1732 $list->description($description);
1733 $list->owner($e->requestor->id);
1734 $list->btype('bookbag');
1735 $list->pub($shared ? 't' : 'f');
1736 $success = $U->simplereq('open-ils.actor',
1737 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1739 } elsif($action eq 'place_hold') {
1741 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1742 unless (@hold_recs) {
1743 if (@selected_item) {
1744 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1745 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1749 return Apache2::Const::OK unless @hold_recs;
1750 $logger->info("placing holds from list page on: @hold_recs");
1752 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1753 $url .= ';hold_target=' . $_ for @hold_recs;
1754 foreach my $param (('loc', 'qtype', 'query')) {
1755 if ($cgi->param($param)) {
1756 $url .= ";$param=" . uri_escape($cgi->param($param));
1759 return $self->generic_redirect($url);
1763 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1765 return Apache2::Const::HTTP_BAD_REQUEST unless
1766 $list and $list->owner == $e->requestor->id;
1769 if($action eq 'delete') {
1770 $success = $U->simplereq('open-ils.actor',
1771 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1773 } elsif($action eq 'show') {
1774 unless($U->is_true($list->pub)) {
1776 $success = $U->simplereq('open-ils.actor',
1777 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1780 } elsif($action eq 'hide') {
1781 if($U->is_true($list->pub)) {
1783 $success = $U->simplereq('open-ils.actor',
1784 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1787 } elsif($action eq 'rename') {
1790 $success = $U->simplereq('open-ils.actor',
1791 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1794 } elsif($action eq 'add_rec') {
1795 foreach my $add_rec (@add_rec) {
1796 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1797 $item->bucket($list_id);
1798 $item->target_biblio_record_entry($add_rec);
1799 $success = $U->simplereq('open-ils.actor',
1800 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1801 last unless $success;
1804 } elsif($action eq 'del_item') {
1805 foreach (@selected_item) {
1806 $success = $U->simplereq(
1808 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1810 last unless $success;
1812 } elsif ($action eq 'save_notes') {
1813 $success = $self->update_bookbag_item_notes;
1814 $url .= "&id=" . uri_escape($cgi->param("id")) if $cgi->param("id");
1817 return $self->generic_redirect($url) if $success;
1819 # XXX FIXME Bucket failure doesn't have a page to show the user anything
1820 # right now. User just sees a 404 currently.
1822 $self->ctx->{bucket_action} = $action;
1823 $self->ctx->{bucket_action_failed} = 1;
1824 return Apache2::Const::OK;
1827 sub update_bookbag_item_notes {
1829 my $e = $self->editor;
1831 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
1832 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
1834 # We're going to leverage an API call that's already been written to check
1835 # permissions appropriately.
1837 my $a = create OpenSRF::AppSession("open-ils.actor");
1838 my $method = "open-ils.actor.container.item_note.cud";
1840 for my $note_key (@note_keys) {
1843 my $id = ($note_key =~ /(\d+)/)[0];
1846 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
1847 my $event = $e->die_event;
1848 $self->apache->log->warn(
1849 "error retrieving cbrebin id $id, got event " .
1853 $self->ctx->{bucket_action_event} = $event;
1857 if (length($self->cgi->param($note_key))) {
1858 $note->ischanged(1);
1859 $note->note($self->cgi->param($note_key));
1861 $note->isdeleted(1);
1864 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1866 if (defined $U->event_code($r)) {
1867 $self->apache->log->warn(
1868 "attempt to modify cbrebin " . $note->id .
1869 " returned event " . $r->{textcode}
1873 $self->ctx->{bucket_action_event} = $r;
1878 for my $item_key (@item_keys) {
1879 my $id = int(($item_key =~ /(\d+)/)[0]);
1880 my $text = $self->cgi->param($item_key);
1883 next unless length $text;
1885 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
1890 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1892 if (defined $U->event_code($r)) {
1893 $self->apache->log->warn(
1894 "attempt to create cbrebin for item " . $note->item .
1895 " returned event " . $r->{textcode}
1899 $self->ctx->{bucket_action_event} = $r;
1908 sub load_myopac_bookbag_print {
1911 my $id = int($self->cgi->param("list"));
1913 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1916 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
1920 # Get the bookbag object itself, assuming we're allowed to.
1921 if ($self->editor->allowed("VIEW_CONTAINER")) {
1923 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1925 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
1929 "owner" => $self->editor->requestor->id,
1933 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1935 $bbag = pop @$bookbags;
1938 # If we have a bookbag we're allowed to look at, issue the A/T event
1939 # to get CSV, passing as a user param that search query we built before.
1941 $self->ctx->{csv} = $U->fire_object_event(
1942 undef, "container.biblio_record_entry_bucket.csv",
1943 $bbag, $self->editor->requestor->home_ou,
1944 undef, {"item_search" => $item_search}
1948 # Create a reasonable filename and set the content disposition to
1949 # provoke browser download dialogs.
1950 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
1952 return $self->set_file_download_headers("$filename.csv");
1955 sub load_myopac_circ_history_export {
1957 my $e = $self->editor;
1958 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
1960 my $ids = $e->json_query({
1964 transform => 'action.usr_visible_circs',
1965 result_field => 'id'
1969 where => {id => $e->requestor->id}
1972 $self->ctx->{csv} = $U->fire_object_event(
1974 'circ.format.history.csv',
1975 $e->search_action_circulation({id => [map {$_->{id}} @$ids]}, {substream =>1}),
1976 $self->editor->requestor->home_ou
1979 return $self->set_file_download_headers($filename);
1982 sub load_password_reset {
1984 my $cgi = $self->cgi;
1985 my $ctx = $self->ctx;
1986 my $barcode = $cgi->param('barcode');
1987 my $username = $cgi->param('username');
1988 my $email = $cgi->param('email');
1989 my $pwd1 = $cgi->param('pwd1');
1990 my $pwd2 = $cgi->param('pwd2');
1991 my $uuid = $ctx->{page_args}->[0];
1995 $logger->info("patron password reset with uuid $uuid");
1997 if ($pwd1 and $pwd2) {
1999 if ($pwd1 eq $pwd2) {
2001 my $response = $U->simplereq(
2003 'open-ils.actor.patron.password_reset.commit',
2006 $logger->info("patron password reset response " . Dumper($response));
2008 if ($U->event_code($response)) { # non-success event
2010 my $code = $response->{textcode};
2012 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2013 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2016 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2017 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2022 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2025 } else { # passwords not equal
2027 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2030 } else { # 2 password values needed
2032 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2035 } elsif ($barcode or $username) {
2037 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2038 push(@params, $email) if $email;
2042 'open-ils.actor.patron.password_reset.request', @params);
2044 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2047 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2048 return Apache2::Const::OK;