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(defined($lock_usernames) and $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) {
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 _load_lists_and_settings {
262 my $e = $self->editor;
263 my $stat = $self->_load_user_with_prefs;
266 my $setting_map = $self->ctx->{user_setting_map};
267 $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
268 $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
270 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
271 order_by => {cbreb => 'name'},
272 limit => $self->cgi->param('limit') || 10,
273 offset => $self->cgi->param('offset') || 0
277 # We also want a total count of the user's bookbags.
279 'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
281 'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
283 my $r = $e->json_query($q);
284 $self->ctx->{bookbag_count} = $r->[0]->{'count'};
285 # Someone has requested that we use the default list's name
286 # rather than "Default List."
289 'select' => {'cbreb' => ['name']},
291 'where' => {'id' => $exclude}
293 $r = $e->json_query($q);
294 $self->ctx->{default_bookbag} = $r->[0]->{'name'};
302 sub update_optin_prefs {
304 my $user_prefs = shift;
305 my $e = $self->editor;
306 my @settings = $self->cgi->param('setting');
309 # apply now-true settings
310 for my $applied (@settings) {
311 # see if setting is already applied to this user
312 next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
313 $newsets{$applied} = OpenSRF::Utils::JSON->true;
316 # remove now-false settings
317 for my $pref (grep { $_->{value} } @$user_prefs) {
318 $newsets{$pref->{cust}->name} = undef
319 unless grep { $_ eq $pref->{cust}->name } @settings;
324 'open-ils.actor.patron.settings.update',
325 $e->authtoken, $e->requestor->id, \%newsets);
327 # update the local prefs to match reality
328 for my $pref (@$user_prefs) {
329 $pref->{value} = $newsets{$pref->{cust}->name}
330 if exists $newsets{$pref->{cust}->name};
336 sub _load_user_with_prefs {
338 my $stat = $self->prepare_extended_user_info('settings');
339 return $stat if $stat; # not-OK
341 $self->ctx->{user_setting_map} = {
342 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
343 @{$self->ctx->{user}->settings}
349 sub _get_bookbag_sort_params {
350 my ($self, $param_name) = @_;
352 # The interface that feeds this cgi parameter will provide a single
353 # argument for a QP sort filter, and potentially a modifier after a period.
354 # In practice this means the "sort" parameter will be something like
355 # "titlesort" or "authorsort.descending".
356 my $sorter = $self->cgi->param($param_name) || "";
359 $sorter =~ s/^(.*?)\.(.*)/$1/;
360 $modifier = $2 || undef;
363 return ($sorter, $modifier);
366 sub _prepare_bookbag_container_query {
367 my ($self, $container_id, $sorter, $modifier) = @_;
370 "container(bre,bookbag,%d,%s)%s%s",
371 $container_id, $self->editor->authtoken,
372 ($sorter ? " sort($sorter)" : ""),
373 ($modifier ? "#$modifier" : "")
377 sub _prepare_anonlist_sorting_query {
378 my ($self, $list, $sorter, $modifier) = @_;
381 "record_list(%s)%s%s",
383 ($sorter ? " sort($sorter)" : ""),
384 ($modifier ? "#$modifier" : "")
389 sub load_myopac_prefs_settings {
394 opac.default_search_location
395 opac.default_pickup_location
396 opac.temporary_list_no_warn
399 my $stat = $self->_load_user_with_prefs;
400 return $stat if $stat;
402 return Apache2::Const::OK
403 unless $self->cgi->request_method eq 'POST';
405 # some setting values from the form don't match the
406 # required value/format for the db, so they have to be
407 # individually translated.
410 my $set_map = $self->ctx->{user_setting_map};
412 foreach my $key (@user_prefs) {
413 my $val = $self->cgi->param($key);
414 $settings{$key}= $val unless $$set_map{$key} eq $val;
417 my $now = DateTime->now->strftime('%F');
418 foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
419 my $val = $self->cgi->param($key);
420 if($val and $val eq 'on') {
421 # Set the start time to 'now' unless a start time already exists for the user
422 $settings{$key} = $now unless $$set_map{$key};
424 # clear the start time if one previously existed for the user
425 $settings{$key} = undef if $$set_map{$key};
429 # Send the modified settings off to be saved
432 'open-ils.actor.patron.settings.update',
433 $self->editor->authtoken, undef, \%settings);
435 # re-fetch user prefs
436 $self->ctx->{updated_user_settings} = \%settings;
437 return $self->_load_user_with_prefs || Apache2::Const::OK;
440 sub fetch_user_holds {
442 my $hold_ids = shift;
443 my $ids_only = shift;
445 my $available = shift;
449 my $e = $self->editor;
452 my $circ = OpenSRF::AppSession->create('open-ils.circ');
454 $hold_ids = $circ->request(
455 'open-ils.circ.holds.id_list.retrieve.authoritative',
461 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
465 return $hold_ids if $ids_only or @$hold_ids == 0;
468 suppress_notices => 1,
469 suppress_transits => 1,
471 suppress_patron_details => 1
474 # ----------------------------------------------------------------
475 # Collect holds in batches of $batch_size for faster retrieval
479 my $mk_req_batch = sub {
481 my $top_idx = $batch_idx + $batch_size;
482 while($batch_idx < $top_idx) {
483 my $hold_id = $hold_ids->[$batch_idx++];
484 last unless $hold_id;
485 my $ses = OpenSRF::AppSession->create('open-ils.circ');
486 my $req = $ses->request(
487 'open-ils.circ.hold.details.retrieve',
488 $e->authtoken, $hold_id, $args);
489 push(@ses, {ses => $ses, req => $req});
495 my(@collected, @holds, @ses);
498 @ses = $mk_req_batch->() if $first;
499 last if $first and not @ses;
502 # If desired by the caller, filter any holds that are not available.
504 @collected = grep { $_->{hold}->{status} == 4 } @collected;
506 while(my $blob = pop(@collected)) {
507 my (undef, @data) = $self->get_records_and_facets(
508 [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
510 $blob->{marc_xml} = $data[0]->{marc_xml};
515 for my $req_data (@ses) {
516 push(@collected, {hold => $req_data->{req}->gather(1)});
517 $req_data->{ses}->kill_me;
520 @ses = $mk_req_batch->();
521 last unless @collected or @ses;
525 # put the holds back into the original server sort order
527 for my $id (@$hold_ids) {
528 push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
534 sub handle_hold_update {
537 my $hold_ids = shift;
538 my $e = $self->editor;
541 my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
542 @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
544 my $circ = OpenSRF::AppSession->create('open-ils.circ');
546 if($action =~ /cancel/) {
548 for my $hold_id (@hold_ids) {
549 my $resp = $circ->request(
550 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
553 } elsif ($action =~ /activate|suspend/) {
556 for my $hold_id (@hold_ids) {
557 my $vals = {id => $hold_id};
559 if($action =~ /activate/) {
560 $vals->{frozen} = 'f';
561 $vals->{thaw_date} = undef;
563 } elsif($action =~ /suspend/) {
564 $vals->{frozen} = 't';
565 # $vals->{thaw_date} = TODO;
567 push(@$vlist, $vals);
570 my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
571 $self->ctx->{hold_suspend_post_capture} = 1 if
572 grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
574 } elsif ($action eq 'edit') {
577 my $val = {"id" => $_};
578 $val->{"frozen"} = $self->cgi->param("frozen");
579 $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
581 for my $field (qw/expire_time thaw_date/) {
582 # XXX TODO make this support other date formats, not just
584 next unless $self->cgi->param($field) =~
585 m:^(\d{2})/(\d{2})/(\d{4})$:;
586 $val->{$field} = "$3-$1-$2";
592 'open-ils.circ.hold.update.batch.atomic',
593 $e->authtoken, undef, \@vals
594 )->gather(1); # LFW XXX test for failure
595 $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
596 foreach my $param (('loc', 'qtype', 'query')) {
597 if ($self->cgi->param($param)) {
598 $url .= ";$param=" . uri_escape($self->cgi->param($param));
604 return defined($url) ? $self->generic_redirect($url) : undef;
607 sub load_myopac_holds {
609 my $e = $self->editor;
610 my $ctx = $self->ctx;
612 my $limit = $self->cgi->param('limit') || 0;
613 my $offset = $self->cgi->param('offset') || 0;
614 my $action = $self->cgi->param('action') || '';
615 my $hold_id = $self->cgi->param('id');
616 my $available = int($self->cgi->param('available') || 0);
618 my $hold_handle_result;
619 $hold_handle_result = $self->handle_hold_update($action) if $action;
621 $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
623 return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
628 sub load_place_hold {
630 my $ctx = $self->ctx;
631 my $gos = $ctx->{get_org_setting};
632 my $e = $self->editor;
633 my $cgi = $self->cgi;
635 $self->ctx->{page} = 'place_hold';
636 my @targets = $cgi->param('hold_target');
637 my @parts = $cgi->param('part');
639 $ctx->{hold_type} = $cgi->param('hold_type');
640 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
641 $ctx->{email_notify} = $cgi->param('email_notify');
642 if ($cgi->param('phone_notify_checkbox')) {
643 $ctx->{phone_notify} = $cgi->param('phone_notify');
645 if ($cgi->param('sms_notify_checkbox')) {
646 $ctx->{sms_notify} = $cgi->param('sms_notify');
647 $ctx->{sms_carrier} = $cgi->param('sms_carrier');
650 return $self->generic_redirect unless @targets;
652 $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
654 $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
659 au => ['settings', 'card']
662 ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
663 my $user_setting_map = {
664 map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
666 $ctx->{staff_recipient}->settings
669 $ctx->{user_setting_map} = $user_setting_map;
671 my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
672 if ($default_notify =~ /email/) {
673 $ctx->{default_email_notify} = 'checked';
675 $ctx->{default_email_notify} = '';
677 if ($default_notify =~ /phone/) {
678 $ctx->{default_phone_notify} = 'checked';
680 $ctx->{default_phone_notify} = '';
682 if ($default_notify =~ /sms/) {
683 $ctx->{default_sms_notify} = 'checked';
685 $ctx->{default_sms_notify} = '';
688 # If we have a default pickup location, grab it
689 if ($$user_setting_map{'opac.default_pickup_location'}) {
690 $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
693 my $request_lib = $e->requestor->ws_ou;
695 $ctx->{hold_data} = \@hold_data;
699 if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
700 if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
701 if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
702 if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
706 my $type_dispatch = {
708 my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
710 for my $id (@targets) { # force back into the correct order
711 my ($rec) = grep {$_->id eq $id} @$recs;
713 # NOTE: if tpac ever supports locked-down pickup libs,
714 # we'll need to pass a pickup_lib param along with the
715 # record to filter the set of monographic parts.
716 my $parts = $U->simplereq(
718 'open-ils.search.biblio.record_hold_parts',
722 # T holds on records that have parts are OK, but if the record has
723 # no non-part copies, the hold will ultimately fail. When that
724 # happens, require the user to select a part.
725 my $part_required = 0;
727 my $np_copies = $e->json_query({
728 select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
729 from => {acp => {acn => {}, acpm => {type => 'left'}}},
731 '+acp' => {deleted => 'f'},
732 '+acn' => {deleted => 'f', record => $rec->id},
733 '+acpm' => {id => undef}
736 $part_required = 1 if $np_copies->[0]->{count} == 0;
739 push(@hold_data, $data_filler->({
743 part_required => $part_required
748 my $vols = $e->batch_retrieve_asset_call_number([
751 "flesh_fields" => {"acn" => ["record"]}
753 ], {substream => 1});
755 for my $id (@targets) {
756 my ($vol) = grep {$_->id eq $id} @$vols;
757 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
761 my $copies = $e->batch_retrieve_asset_copy([
766 "acp" => ["call_number"]
769 ], {substream => 1});
771 for my $id (@targets) {
772 my ($copy) = grep {$_->id eq $id} @$copies;
773 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
777 my $isses = $e->batch_retrieve_serial_issuance([
781 "siss" => ["subscription"], "ssub" => ["record_entry"]
784 ], {substream => 1});
786 for my $id (@targets) {
787 my ($iss) = grep {$_->id eq $id} @$isses;
788 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
793 }->{$ctx->{hold_type}}->();
795 # caller sent bad target IDs or the wrong hold type
796 return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
798 # generate the MARC xml for each record
799 $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
801 my $pickup_lib = $cgi->param('pickup_lib');
802 # no pickup lib means no holds placement
803 return Apache2::Const::OK unless $pickup_lib;
805 $ctx->{hold_attempt_made} = 1;
807 # Give the original CGI params back to the user in case they
808 # want to try to override something.
809 $ctx->{orig_params} = $cgi->Vars;
810 delete $ctx->{orig_params}{submit};
811 delete $ctx->{orig_params}{hold_target};
812 delete $ctx->{orig_params}{part};
814 my $usr = $e->requestor->id;
816 if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
817 # find the real hold target
819 $usr = $U->simplereq(
821 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
822 $e->authtoken, $cgi->param("hold_usr"));
824 if (defined $U->event_code($usr)) {
825 $ctx->{hold_failed} = 1;
826 $ctx->{hold_failed_event} = $usr;
830 # target_id is the true target_id for holds placement.
831 # needed for attempt_hold_placement()
832 # With the exception of P-type holds, target_id == target->id.
833 $_->{target_id} = $_->{target}->id for @hold_data;
835 if ($ctx->{hold_type} eq 'T') {
837 # Much like quantum wave-particles, P-type holds pop into
838 # and out of existence at the user's whim. For our purposes,
839 # we treat such holds as T(itle) holds with a selected_part
840 # designation. When the time comes to pass the hold information
841 # off for holds possibility testing and placement, make it look
842 # like a real P-type hold.
843 my (@p_holds, @t_holds);
845 for my $idx (0..$#parts) {
846 my $hdata = $hold_data[$idx];
847 if (my $part = $parts[$idx]) {
848 $hdata->{target_id} = $part;
849 $hdata->{selected_part} = $part;
850 push(@p_holds, $hdata);
852 push(@t_holds, $hdata);
856 $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
857 $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
860 $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
863 # NOTE: we are leaving the staff-placed patron barcode cookie
864 # in place. Otherwise, it's not possible to place more than
865 # one hold for the patron within a staff/patron session. This
866 # does leave the barcode to linger longer than is ideal, but
867 # normal staff work flow will cause the cookie to be replaced
868 # with each new patron anyway.
869 # TODO: See about getting the staff client to clear the cookie
871 # return to the place_hold page so the results of the hold
872 # placement attempt can be reported to the user
873 return Apache2::Const::OK;
876 sub attempt_hold_placement {
877 my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
878 my $cgi = $self->cgi;
879 my $ctx = $self->ctx;
880 my $e = $self->editor;
882 # First see if we should warn/block for any holds that
883 # might have locally available items.
884 for my $hdata (@hold_data) {
885 my ($local_block, $local_alert) = $self->local_avail_concern(
886 $hdata->{target_id}, $hold_type, $pickup_lib);
889 $hdata->{hold_failed} = 1;
890 $hdata->{hold_local_block} = 1;
891 } elsif ($local_alert) {
892 $hdata->{hold_failed} = 1;
893 $hdata->{hold_local_alert} = 1;
897 my $method = 'open-ils.circ.holds.test_and_create.batch';
899 if ($cgi->param('override')) {
900 $method .= '.override';
902 } elsif (!$ctx->{is_staff}) {
904 $method .= '.override' if $self->ctx->{get_org_setting}->(
905 $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
908 my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
910 if(@create_targets) {
912 my $bses = OpenSRF::AppSession->create('open-ils.circ');
913 my $breq = $bses->request(
916 $data_filler->({ patronid => $usr,
917 pickup_lib => $pickup_lib,
918 hold_type => $hold_type
923 while (my $resp = $breq->recv) {
925 $resp = $resp->content;
926 $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
928 if ($U->event_code($resp)) {
929 $ctx->{general_hold_error} = $resp;
933 my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
934 my $result = $resp->{result};
936 if ($U->event_code($result)) {
937 # e.g. permission denied
938 $hdata->{hold_failed} = 1;
939 $hdata->{hold_failed_event} = $result;
943 if(not ref $result and $result > 0) {
944 # successul hold returns the hold ID
946 $hdata->{hold_success} = $result;
949 # hold-specific failure event
950 $hdata->{hold_failed} = 1;
952 if (ref $result eq 'HASH') {
953 $hdata->{hold_failed_event} = $result->{last_event};
955 if ($result->{age_protected_copy}) {
956 $hdata->{could_override} = 1;
957 $hdata->{age_protect} = 1;
959 $hdata->{could_override} = $result->{place_unfillable} ||
960 $self->test_could_override($hdata->{hold_failed_event});
962 } elsif (ref $result eq 'ARRAY') {
963 $hdata->{hold_failed_event} = $result->[0];
965 if ($result->[3]) { # age_protect_only
966 $hdata->{could_override} = 1;
967 $hdata->{age_protect} = 1;
969 $hdata->{could_override} = $result->[4] || # place_unfillable
970 $self->test_could_override($hdata->{hold_failed_event});
981 sub fetch_user_circs {
983 my $flesh = shift; # flesh bib data, etc.
984 my $circ_ids = shift;
988 my $e = $self->editor;
993 @circ_ids = @$circ_ids;
998 select => {circ => ['id']},
1002 usr => $e->requestor->id,
1003 checkin_time => undef,
1005 {stop_fines => undef},
1006 {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1010 order_by => {circ => ['due_date']}
1013 $query->{limit} = $limit if $limit;
1014 $query->{offset} = $offset if $offset;
1016 my $ids = $e->json_query($query);
1017 @circ_ids = map {$_->{id}} @$ids;
1020 return [] unless @circ_ids;
1025 circ => ['target_copy'],
1026 acp => ['call_number'],
1032 my $circs = $e->search_action_circulation(
1033 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1036 for my $circ (@$circs) {
1039 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
1040 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
1041 undef # pre-cat copy, use the dummy title/author instead
1046 # make sure the final list is in the correct order
1048 for my $id (@circ_ids) {
1051 (grep { $_->{circ}->id == $id } @circs)
1055 return \@sorted_circs;
1059 sub handle_circ_renew {
1062 my $ctx = $self->ctx;
1064 my @renew_ids = $self->cgi->param('circ');
1066 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1068 # TODO: fire off renewal calls in batches to speed things up
1070 for my $circ (@$circs) {
1072 my $evt = $U->simplereq(
1074 'open-ils.circ.renew',
1075 $self->editor->authtoken,
1077 patron_id => $self->editor->requestor->id,
1078 copy_id => $circ->{circ}->target_copy,
1083 # TODO return these, then insert them into the circ data
1084 # blob that is shoved into the template for each circ
1085 # so the template won't have to match them
1086 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1093 sub load_myopac_circs {
1095 my $e = $self->editor;
1096 my $ctx = $self->ctx;
1099 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1100 my $offset = $self->cgi->param('offset') || 0;
1101 my $action = $self->cgi->param('action') || '';
1103 # perform the renewal first if necessary
1104 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1106 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1108 my $success_renewals = 0;
1109 my $failed_renewals = 0;
1110 for my $data (@{$ctx->{circs}}) {
1111 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1114 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1115 $data->{renewal_response} = $evt;
1116 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1117 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1121 $ctx->{success_renewals} = $success_renewals;
1122 $ctx->{failed_renewals} = $failed_renewals;
1124 return Apache2::Const::OK;
1127 sub load_myopac_circ_history {
1129 my $e = $self->editor;
1130 my $ctx = $self->ctx;
1131 my $limit = $self->cgi->param('limit') || 15;
1132 my $offset = $self->cgi->param('offset') || 0;
1134 $ctx->{circ_history_limit} = $limit;
1135 $ctx->{circ_history_offset} = $offset;
1137 my $circ_ids = $e->json_query({
1141 transform => 'action.usr_visible_circs',
1142 result_field => 'id'
1146 where => {id => $e->requestor->id},
1151 $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1152 return Apache2::Const::OK;
1155 # TODO: action.usr_visible_holds does not return cancelled holds. Should it?
1156 sub load_myopac_hold_history {
1158 my $e = $self->editor;
1159 my $ctx = $self->ctx;
1160 my $limit = $self->cgi->param('limit') || 15;
1161 my $offset = $self->cgi->param('offset') || 0;
1162 $ctx->{hold_history_limit} = $limit;
1163 $ctx->{hold_history_offset} = $offset;
1165 my $hold_ids = $e->json_query({
1169 transform => 'action.usr_visible_holds',
1170 result_field => 'id'
1174 where => {id => $e->requestor->id},
1179 $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
1180 return Apache2::Const::OK;
1183 sub load_myopac_payment_form {
1187 $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1188 $r = $self->prepare_extended_user_info and return $r;
1190 return Apache2::Const::OK;
1193 # TODO: add other filter options as params/configs/etc.
1194 sub load_myopac_payments {
1196 my $limit = $self->cgi->param('limit') || 20;
1197 my $offset = $self->cgi->param('offset') || 0;
1198 my $e = $self->editor;
1200 $self->ctx->{payment_history_limit} = $limit;
1201 $self->ctx->{payment_history_offset} = $offset;
1204 $args->{limit} = $limit if $limit;
1205 $args->{offset} = $offset if $offset;
1207 if (my $max_age = $self->ctx->{get_org_setting}->(
1208 $e->requestor->home_ou, "opac.payment_history_age_limit"
1210 my $min_ts = DateTime->now(
1211 "time_zone" => DateTime::TimeZone->new("name" => "local"),
1212 )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1214 $logger->info("XXX min_ts: $min_ts");
1215 $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1218 $self->ctx->{payments} = $U->simplereq(
1220 'open-ils.actor.user.payments.retrieve.atomic',
1221 $e->authtoken, $e->requestor->id, $args);
1223 return Apache2::Const::OK;
1226 # 1. caches the form parameters
1227 # 2. loads the credit card payment "Processing..." page
1228 sub load_myopac_pay_init {
1230 my $cache = OpenSRF::Utils::Cache->new('global');
1232 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1234 if (!@payment_xacts) {
1235 # for consistency with load_myopac_payment_form() and
1236 # to preserve backwards compatibility, if no xacts are
1237 # selected, assume all (applicable) transactions are wanted.
1238 my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1239 return $stat if $stat;
1241 map { $_->{xact}->id } (
1242 @{$self->ctx->{fines}->{circulation}},
1243 @{$self->ctx->{fines}->{grocery}}
1247 return $self->generic_redirect unless @payment_xacts;
1249 my $cc_args = {"where_process" => 1};
1251 $cc_args->{$_} = $self->cgi->param($_) for (qw/
1252 number cvv2 expire_year expire_month billing_first
1253 billing_last billing_address billing_city billing_state
1258 cc_args => $cc_args,
1259 user => $self->ctx->{user}->id,
1260 xacts => \@payment_xacts
1263 # generate a temporary cache token and cache the form data
1264 my $token = md5_hex($$ . time() . rand());
1265 $cache->put_cache($token, $cache_args, 30);
1267 $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1269 # after we render the processing page, we quickly redirect to submit
1270 # the actual payment. The refresh url contains the payment token.
1271 # It also contains the list of xact IDs, which allows us to clear the
1272 # cache at the earliest possible time while leaving a trace of which
1273 # transactions we were processing, so the UI can bring the user back
1274 # to the payment form w/ the same xacts if the payment fails.
1276 my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1277 $refresh .= ";xact=$_" for @payment_xacts;
1278 $self->ctx->{refresh} = $refresh;
1280 return Apache2::Const::OK;
1283 # retrieve the cached CC payment info and send off for processing
1284 sub load_myopac_pay {
1286 my $token = $self->ctx->{page_args}->[0];
1287 return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1289 my $cache = OpenSRF::Utils::Cache->new('global');
1290 my $cache_args = $cache->get_cache($token);
1291 $cache->delete_cache($token);
1293 # this page is loaded immediately after the token is created.
1294 # if the cached data is not there, it's because of an invalid
1295 # token (or cache failure) and not because of a timeout.
1296 return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1298 my @payment_xacts = @{$cache_args->{xacts}};
1299 my $cc_args = $cache_args->{cc_args};
1301 # as an added security check, verify the user submitting
1302 # the form is the same as the user whose data was cached
1303 return Apache2::Const::HTTP_BAD_REQUEST unless
1304 $cache_args->{user} == $self->ctx->{user}->id;
1306 $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1309 $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1311 # balance_owed is computed specifically from the fines we're paying
1312 if ($self->ctx->{fines}->{balance_owed} <= 0) {
1313 $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1314 return Apache2::Const::HTTP_BAD_REQUEST;
1318 "cc_args" => $cc_args,
1319 "userid" => $self->ctx->{user}->id,
1320 "payment_type" => "credit_card_payment",
1321 "payments" => $self->prepare_fines_for_payment # should be safe after self->prepare_fines
1324 my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1325 $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1328 $self->ctx->{"payment_response"} = $resp;
1330 unless ($resp->{"textcode"}) {
1331 $self->ctx->{printable_receipt} = $U->simplereq(
1332 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1333 $self->editor->authtoken, $resp->{payments}
1337 return Apache2::Const::OK;
1340 sub load_myopac_receipt_print {
1343 $self->ctx->{printable_receipt} = $U->simplereq(
1344 "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1345 $self->editor->authtoken, [$self->cgi->param("payment")]
1348 return Apache2::Const::OK;
1351 sub load_myopac_receipt_email {
1354 # The following ML method doesn't actually check whether the user in
1355 # question has an email address, so we do.
1356 if ($self->ctx->{user}->email) {
1357 $self->ctx->{email_receipt_result} = $U->simplereq(
1358 "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1359 $self->editor->authtoken, [$self->cgi->param("payment")]
1362 $self->ctx->{email_receipt_result} =
1363 new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1366 return Apache2::Const::OK;
1370 my ($self, $limit, $offset, $id_list) = @_;
1372 # XXX TODO: check for failure after various network calls
1374 # It may be unclear, but this result structure lumps circulation and
1375 # reservation fines together, and keeps grocery fines separate.
1376 $self->ctx->{"fines"} = {
1377 "circulation" => [],
1384 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1386 # TODO: This should really be a ML call, but the existing calls
1387 # return an excessive amount of data and don't offer streaming
1389 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1391 my $req = $cstore->request(
1392 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1394 usr => $self->editor->requestor->id,
1395 balance_owed => {'!=' => 0},
1396 ($id_list && @$id_list ? ("id" => $id_list) : ()),
1401 mobts => [qw/grocery circulation reservation/],
1402 bresv => ['target_resource_type'],
1406 circ => ['target_copy'],
1407 acp => ['call_number'],
1410 order_by => { mobts => 'xact_start' },
1415 my @total_keys = qw/total_paid total_owed balance_owed/;
1416 $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1418 while(my $resp = $req->recv) {
1419 my $mobts = $resp->content;
1420 my $circ = $mobts->circulation;
1423 if($mobts->grocery) {
1424 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1425 $last_billing = pop(@billings);
1428 # XXX TODO confirm that the following, and the later division by 100.0
1429 # to get a floating point representation once again, is sufficiently
1430 # "money-safe" math.
1431 $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1433 my $marc_xml = undef;
1434 if ($mobts->xact_type eq 'reservation' and
1435 $mobts->reservation->target_resource_type->record) {
1436 $marc_xml = XML::LibXML->new->parse_string(
1437 $mobts->reservation->target_resource_type->record->marc
1439 } elsif ($mobts->xact_type eq 'circulation' and
1440 $circ->target_copy->call_number->id != -1) {
1441 $marc_xml = XML::LibXML->new->parse_string(
1442 $circ->target_copy->call_number->record->marc
1447 @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1450 last_grocery_billing => $last_billing,
1451 marc_xml => $marc_xml
1458 $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1462 sub prepare_fines_for_payment {
1463 # This assumes $self->prepare_fines has already been run
1467 if ($self->ctx->{fines}) {
1468 push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1469 @{$self->ctx->{fines}->{circulation}},
1470 @{$self->ctx->{fines}->{grocery}}
1477 sub load_myopac_main {
1479 my $limit = $self->cgi->param('limit') || 0;
1480 my $offset = $self->cgi->param('offset') || 0;
1481 $self->ctx->{search_ou} = $self->_get_search_lib();
1482 $self->ctx->{user}->notes(
1483 $self->editor->search_actor_usr_note({
1484 usr => $self->ctx->{user}->id,
1488 return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1491 sub load_myopac_update_email {
1493 my $e = $self->editor;
1494 my $ctx = $self->ctx;
1495 my $email = $self->cgi->param('email') || '';
1496 my $current_pw = $self->cgi->param('current_pw') || '';
1498 # needed for most up-to-date email address
1499 if (my $r = $self->prepare_extended_user_info) { return $r };
1501 return Apache2::Const::OK
1502 unless $self->cgi->request_method eq 'POST';
1504 unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1505 $ctx->{invalid_email} = $email;
1506 return Apache2::Const::OK;
1509 my $stat = $U->simplereq(
1511 'open-ils.actor.user.email.update',
1512 $e->authtoken, $email, $current_pw);
1514 if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1515 $ctx->{password_incorrect} = 1;
1516 return Apache2::Const::OK;
1519 unless ($self->cgi->param("redirect_to")) {
1520 my $url = $self->apache->unparsed_uri;
1521 $url =~ s/update_email/prefs/;
1523 return $self->generic_redirect($url);
1526 return $self->generic_redirect;
1529 sub load_myopac_update_username {
1531 my $e = $self->editor;
1532 my $ctx = $self->ctx;
1533 my $username = $self->cgi->param('username') || '';
1534 my $current_pw = $self->cgi->param('current_pw') || '';
1536 $self->prepare_extended_user_info;
1538 my $allow_change = 1;
1540 my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1541 if(defined($lock_usernames) and $lock_usernames == 1) {
1542 # Policy says no username changes
1545 # We want this further down.
1546 $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1547 my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1548 if(!$username_unlimit) {
1550 # Default is "starts with a number"
1551 $regex_check = '^\d+';
1553 # You already have a username?
1554 if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1559 if(!$allow_change) {
1560 my $url = $self->apache->unparsed_uri;
1561 $url =~ s/update_username/prefs/;
1563 return $self->generic_redirect($url);
1566 return Apache2::Const::OK
1567 unless $self->cgi->request_method eq 'POST';
1569 unless($username and $username !~ /\s/) { # any other username restrictions?
1570 $ctx->{invalid_username} = $username;
1571 return Apache2::Const::OK;
1574 # New username can't look like a barcode if we have a barcode regex
1575 if($regex_check and $username =~ /$regex_check/) {
1576 $ctx->{invalid_username} = $username;
1577 return Apache2::Const::OK;
1580 # New username has to look like a username if we have a username regex
1581 $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1582 if($regex_check and $username !~ /$regex_check/) {
1583 $ctx->{invalid_username} = $username;
1584 return Apache2::Const::OK;
1587 if($username ne $e->requestor->usrname) {
1589 my $evt = $U->simplereq(
1591 'open-ils.actor.user.username.update',
1592 $e->authtoken, $username, $current_pw);
1594 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1595 $ctx->{password_incorrect} = 1;
1596 return Apache2::Const::OK;
1599 if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1600 $ctx->{username_exists} = $username;
1601 return Apache2::Const::OK;
1605 my $url = $self->apache->unparsed_uri;
1606 $url =~ s/update_username/prefs/;
1608 return $self->generic_redirect($url);
1611 sub load_myopac_update_password {
1613 my $e = $self->editor;
1614 my $ctx = $self->ctx;
1616 return Apache2::Const::OK
1617 unless $self->cgi->request_method eq 'POST';
1619 my $current_pw = $self->cgi->param('current_pw') || '';
1620 my $new_pw = $self->cgi->param('new_pw') || '';
1621 my $new_pw2 = $self->cgi->param('new_pw2') || '';
1623 unless($new_pw eq $new_pw2) {
1624 $ctx->{password_nomatch} = 1;
1625 return Apache2::Const::OK;
1628 my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1631 # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1632 $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1635 if($pw_regex and $new_pw !~ /$pw_regex/) {
1636 $ctx->{password_invalid} = 1;
1637 return Apache2::Const::OK;
1640 my $evt = $U->simplereq(
1642 'open-ils.actor.user.password.update',
1643 $e->authtoken, $new_pw, $current_pw);
1646 if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1647 $ctx->{password_incorrect} = 1;
1648 return Apache2::Const::OK;
1651 my $url = $self->apache->unparsed_uri;
1652 $url =~ s/update_password/prefs/;
1654 return $self->generic_redirect($url);
1657 sub _update_bookbag_metadata {
1658 my ($self, $bookbag) = @_;
1660 $bookbag->name($self->cgi->param("name"));
1661 $bookbag->description($self->cgi->param("description"));
1663 return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1667 sub load_myopac_bookbags {
1669 my $e = $self->editor;
1670 my $ctx = $self->ctx;
1671 my $limit = $self->cgi->param('limit') || 10;
1672 my $offset = $self->cgi->param('offset') || 0;
1674 $ctx->{bookbags_limit} = $limit;
1675 $ctx->{bookbags_offset} = $offset;
1677 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1678 $e->xact_begin; # replication...
1680 my $rv = $self->load_mylist;
1681 unless($rv eq Apache2::Const::OK) {
1686 $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1688 {owner => $e->requestor->id, btype => 'bookbag'}, {
1689 order_by => {cbreb => 'name'},
1697 if(!$ctx->{bookbags}) {
1699 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1702 # We load the user prefs to get their default bookbag.
1703 $self->_load_user_with_prefs;
1705 # If the user wants a specific bookbag's items, load them.
1706 # XXX add bookbag item paging support
1708 if ($self->cgi->param("bbid")) {
1710 grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
1713 if ( ($self->cgi->param("action") || '') eq "editmeta") {
1714 if (!$self->_update_bookbag_metadata($bookbag)) {
1716 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1719 my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
1722 foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
1723 if ($self->cgi->param($param)) {
1724 $url .= ";$param=" . uri_escape($self->cgi->param($param));
1728 return $self->generic_redirect($url);
1732 my $query = $self->_prepare_bookbag_container_query(
1733 $bookbag->id, $sorter, $modifier
1736 # XXX Limiting to 1000 for now. This way you should be able to see entire
1737 # list contents. Need to add paging here instead.
1743 my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
1744 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1746 my (undef, @recs) = $self->get_records_and_facets(
1747 [ map {$_->target_biblio_record_entry->id} @$items ],
1752 $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1754 $bookbag->items($items);
1758 # If we have add_rec, we got here from the "Add to new list"
1759 # or "See all" popmenu items.
1760 if (my $add_rec = $self->cgi->param('add_rec')) {
1761 $self->ctx->{add_rec} = $add_rec;
1762 $self->ctx->{where_from} = $self->ctx->{referer};
1763 if ( my $anchor = $self->cgi->param('anchor') ) {
1764 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
1769 return Apache2::Const::OK;
1773 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1774 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1775 sub load_myopac_bookbag_update {
1776 my ($self, $action, $list_id, @hold_recs) = @_;
1777 my $e = $self->editor;
1778 my $cgi = $self->cgi;
1780 # save_notes is effectively another action, but is passed in a separate
1781 # CGI parameter for what are really just layout reasons.
1782 $action = 'save_notes' if $cgi->param('save_notes');
1783 $action ||= $cgi->param('action');
1785 $list_id ||= $cgi->param('list') || $cgi->param('bbid');
1787 my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1788 my @selected_item = $cgi->param('selected_item');
1789 my $shared = $cgi->param('shared');
1790 my $name = $cgi->param('name');
1791 my $description = $cgi->param('description');
1795 # This url intentionally leaves off the edit_notes parameter, but
1796 # may need to add some back in for paging.
1798 my $url = "https://" . $self->apache->hostname .
1799 $self->ctx->{opac_root} . "/myopac/lists?";
1801 foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1802 if ($cgi->param($param)) {
1803 $url .= "$param=" . uri_escape($cgi->param($param)) . ";";
1807 if ($action eq 'create') {
1808 $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1810 $list->description($description);
1811 $list->owner($e->requestor->id);
1812 $list->btype('bookbag');
1813 $list->pub($shared ? 't' : 'f');
1814 $success = $U->simplereq('open-ils.actor',
1815 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
1816 if (ref($success) ne 'HASH' && scalar @add_rec) {
1817 $list_id = (ref($success)) ? $success->id : $success;
1818 foreach my $add_rec (@add_rec) {
1819 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1820 $item->bucket($list_id);
1821 $item->target_biblio_record_entry($add_rec);
1822 $success = $U->simplereq('open-ils.actor',
1823 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1824 last unless $success;
1826 $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
1828 } elsif($action eq 'place_hold') {
1830 # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1831 unless (@hold_recs) {
1832 if (@selected_item) {
1833 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1834 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1838 return Apache2::Const::OK unless @hold_recs;
1839 $logger->info("placing holds from list page on: @hold_recs");
1841 my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1842 $url .= ';hold_target=' . $_ for @hold_recs;
1843 foreach my $param (('loc', 'qtype', 'query')) {
1844 if ($cgi->param($param)) {
1845 $url .= ";$param=" . uri_escape($cgi->param($param));
1848 return $self->generic_redirect($url);
1852 $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1854 return Apache2::Const::HTTP_BAD_REQUEST unless
1855 $list and $list->owner == $e->requestor->id;
1858 if($action eq 'delete') {
1859 $success = $U->simplereq('open-ils.actor',
1860 'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1862 # We check to see if we're deleting the user's default list.
1863 $self->_load_user_with_prefs;
1864 my $settings_map = $self->ctx->{user_setting_map};
1865 if ($$settings_map{'opac.default_list'} == $list_id) {
1866 # We unset the user's opac.default_list setting.
1867 $success = $U->simplereq(
1869 'open-ils.actor.patron.settings.update',
1872 { 'opac.default_list' => 0 }
1876 } elsif($action eq 'show') {
1877 unless($U->is_true($list->pub)) {
1879 $success = $U->simplereq('open-ils.actor',
1880 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1883 } elsif($action eq 'hide') {
1884 if($U->is_true($list->pub)) {
1886 $success = $U->simplereq('open-ils.actor',
1887 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1890 } elsif($action eq 'rename') {
1893 $success = $U->simplereq('open-ils.actor',
1894 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1897 } elsif($action eq 'add_rec') {
1898 foreach my $add_rec (@add_rec) {
1899 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1900 $item->bucket($list_id);
1901 $item->target_biblio_record_entry($add_rec);
1902 $success = $U->simplereq('open-ils.actor',
1903 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1904 last unless $success;
1906 # Redirect back where we came from if we have an anchor parameter:
1907 if ( my $anchor = $cgi->param('anchor') ) {
1908 $url = $self->ctx->{referer};
1909 $url =~ s/#.*|$/#$anchor/;
1910 } elsif ($cgi->param('where_from')) {
1911 # Or, if we have a "where_from" parameter.
1912 $url = $cgi->param('where_from');
1914 } elsif ($action eq 'del_item') {
1915 foreach (@selected_item) {
1916 $success = $U->simplereq(
1918 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1920 last unless $success;
1922 } elsif ($action eq 'save_notes') {
1923 $success = $self->update_bookbag_item_notes;
1924 $url .= "&bbid=" . uri_escape($cgi->param("bbid")) if $cgi->param("bbid");
1925 } elsif ($action eq 'make_default') {
1926 $success = $U->simplereq(
1928 'open-ils.actor.patron.settings.update',
1931 { 'opac.default_list' => $list_id }
1933 } elsif ($action eq 'remove_default') {
1934 $success = $U->simplereq(
1936 'open-ils.actor.patron.settings.update',
1939 { 'opac.default_list' => 0 }
1943 return $self->generic_redirect($url) if $success;
1945 # XXX FIXME Bucket failure doesn't have a page to show the user anything
1946 # right now. User just sees a 404 currently.
1948 $self->ctx->{bucket_action} = $action;
1949 $self->ctx->{bucket_action_failed} = 1;
1950 return Apache2::Const::OK;
1953 sub update_bookbag_item_notes {
1955 my $e = $self->editor;
1957 my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
1958 my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
1960 # We're going to leverage an API call that's already been written to check
1961 # permissions appropriately.
1963 my $a = create OpenSRF::AppSession("open-ils.actor");
1964 my $method = "open-ils.actor.container.item_note.cud";
1966 for my $note_key (@note_keys) {
1969 my $id = ($note_key =~ /(\d+)/)[0];
1972 $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
1973 my $event = $e->die_event;
1974 $self->apache->log->warn(
1975 "error retrieving cbrebin id $id, got event " .
1979 $self->ctx->{bucket_action_event} = $event;
1983 if (length($self->cgi->param($note_key))) {
1984 $note->ischanged(1);
1985 $note->note($self->cgi->param($note_key));
1987 $note->isdeleted(1);
1990 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1992 if (defined $U->event_code($r)) {
1993 $self->apache->log->warn(
1994 "attempt to modify cbrebin " . $note->id .
1995 " returned event " . $r->{textcode}
1999 $self->ctx->{bucket_action_event} = $r;
2004 for my $item_key (@item_keys) {
2005 my $id = int(($item_key =~ /(\d+)/)[0]);
2006 my $text = $self->cgi->param($item_key);
2009 next unless length $text;
2011 my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2016 my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2018 if (defined $U->event_code($r)) {
2019 $self->apache->log->warn(
2020 "attempt to create cbrebin for item " . $note->item .
2021 " returned event " . $r->{textcode}
2025 $self->ctx->{bucket_action_event} = $r;
2034 sub load_myopac_bookbag_print {
2037 my $id = int($self->cgi->param("list"));
2039 my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2042 $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2046 # Get the bookbag object itself, assuming we're allowed to.
2047 if ($self->editor->allowed("VIEW_CONTAINER")) {
2049 $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2051 my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2055 "owner" => $self->editor->requestor->id,
2059 ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2061 $bbag = pop @$bookbags;
2064 # If we have a bookbag we're allowed to look at, issue the A/T event
2065 # to get CSV, passing as a user param that search query we built before.
2067 $self->ctx->{csv} = $U->fire_object_event(
2068 undef, "container.biblio_record_entry_bucket.csv",
2069 $bbag, $self->editor->requestor->home_ou,
2070 undef, {"item_search" => $item_search}
2074 # Create a reasonable filename and set the content disposition to
2075 # provoke browser download dialogs.
2076 (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2078 return $self->set_file_download_headers("$filename.csv");
2081 sub load_myopac_circ_history_export {
2083 my $e = $self->editor;
2084 my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2086 my $ids = $e->json_query({
2090 transform => 'action.usr_visible_circs',
2091 result_field => 'id'
2095 where => {id => $e->requestor->id}
2098 $self->ctx->{csv} = $U->fire_object_event(
2100 'circ.format.history.csv',
2101 $e->search_action_circulation({id => [map {$_->{id}} @$ids]}, {substream =>1}),
2102 $self->editor->requestor->home_ou
2105 return $self->set_file_download_headers($filename);
2108 sub load_password_reset {
2110 my $cgi = $self->cgi;
2111 my $ctx = $self->ctx;
2112 my $barcode = $cgi->param('barcode');
2113 my $username = $cgi->param('username');
2114 my $email = $cgi->param('email');
2115 my $pwd1 = $cgi->param('pwd1');
2116 my $pwd2 = $cgi->param('pwd2');
2117 my $uuid = $ctx->{page_args}->[0];
2121 $logger->info("patron password reset with uuid $uuid");
2123 if ($pwd1 and $pwd2) {
2125 if ($pwd1 eq $pwd2) {
2127 my $response = $U->simplereq(
2129 'open-ils.actor.patron.password_reset.commit',
2132 $logger->info("patron password reset response " . Dumper($response));
2134 if ($U->event_code($response)) { # non-success event
2136 my $code = $response->{textcode};
2138 if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2139 $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2142 if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2143 $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2148 $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2151 } else { # passwords not equal
2153 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2156 } else { # 2 password values needed
2158 $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2161 } elsif ($barcode or $username) {
2163 my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2164 push(@params, $email) if $email;
2168 'open-ils.actor.patron.password_reset.request', @params);
2170 $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2173 $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2174 return Apache2::Const::OK;