]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
TPAC: Add "preferred search location" preference setting
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Account.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 use OpenILS::Event;
9 use OpenSRF::Utils::JSON;
10 use Data::Dumper;
11 $Data::Dumper::Indent = 0;
12 use DateTime;
13 my $U = 'OpenILS::Application::AppUtils';
14
15 sub prepare_extended_user_info {
16     my $self = shift;
17     my @extra_flesh = @_;
18     my $e = $self->editor;
19
20     # are we already in a transaction?
21     my $local_xact = !$e->{xact_id}; 
22     $e->xact_begin if $local_xact;
23
24     $self->ctx->{user} = $self->editor->retrieve_actor_user([
25         $self->ctx->{user}->id,
26         {
27             flesh => 1,
28             flesh_fields => {
29                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
30                 # ...
31             }
32         }
33     ]);
34
35     $e->rollback if $local_xact;
36
37     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR 
38         unless $self->ctx->{user};
39
40     return;
41 }
42
43 # Given an event returned by a failed attempt to create a hold, do we have
44 # permission to override?  XXX Should the permission check be scoped to a
45 # given org_unit context?
46 sub test_could_override {
47     my ($self, $event) = @_;
48
49     return 0 unless $event;
50     return 1 if $self->editor->allowed($event->{textcode} . ".override");
51     return 1 if $event->{"fail_part"} and
52         $self->editor->allowed($event->{"fail_part"} . ".override");
53     return 0;
54 }
55
56 # Find out whether we care that local copies are available
57 sub local_avail_concern {
58     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
59
60     my $would_block = $self->ctx->{get_org_setting}->
61         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
62     my $would_alert = (
63         $self->ctx->{get_org_setting}->
64             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
65                 not $self->cgi->param("override")
66     ) unless $would_block;
67
68     if ($would_block or $would_alert) {
69         my $args = {
70             "hold_target" => $hold_target,
71             "hold_type" => $hold_type,
72             "org_unit" => $pickup_lib
73         };
74         my $local_avail = $U->simplereq(
75             "open-ils.circ",
76             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
77         );
78         $logger->info(
79             "copy availability information for " . Dumper($args) .
80             " is " . Dumper($local_avail)
81         );
82         if (%$local_avail) { # if hash not empty
83             $self->ctx->{hold_copy_available} = $local_avail;
84             return ($would_block, $would_alert);
85         }
86     }
87
88     return (0, 0);
89 }
90
91 # context additions: 
92 #   user : au object, fleshed
93 sub load_myopac_prefs {
94     my $self = shift;
95     my $cgi = $self->cgi;
96     my $e = $self->editor;
97     my $pending_addr = $cgi->param('pending_addr');
98     my $replace_addr = $cgi->param('replace_addr');
99     my $delete_pending = $cgi->param('delete_pending');
100
101     $self->prepare_extended_user_info;
102     my $user = $self->ctx->{user};
103
104     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
105     if($lock_usernames == 1) {
106         # Policy says no username changes
107         $self->ctx->{username_change_disallowed} = 1;
108     } else {
109         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
110         if($username_unlimit != 1) {
111             my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
112             if(!$regex_check) {
113                 # Default is "starts with a number"
114                 $regex_check = '^\d+';
115             }
116             # You already have a username?
117             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
118                 $self->ctx->{username_change_disallowed} = 1;
119             }
120         }
121     }
122
123     return Apache2::Const::OK unless 
124         $pending_addr or $replace_addr or $delete_pending;
125
126     my @form_fields = qw/address_type street1 street2 city county state country post_code/;
127
128     my $paddr;
129     if( $pending_addr ) { # update an existing pending address
130
131         ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
132         return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
133         $paddr->$_( $cgi->param($_) ) for @form_fields;
134
135     } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
136
137         $paddr = Fieldmapper::actor::user_address->new;
138         $paddr->isnew(1);
139         $paddr->usr($user->id);
140         $paddr->pending('t');
141         $paddr->replaces($replace_addr);
142         $paddr->$_( $cgi->param($_) ) for @form_fields;
143
144     } elsif( $delete_pending ) {
145         $paddr = $e->retrieve_actor_user_address($delete_pending);
146         return Apache2::Const::HTTP_BAD_REQUEST unless 
147             $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
148         $paddr->isdeleted(1);
149     }
150
151     my $resp = $U->simplereq(
152         'open-ils.actor', 
153         'open-ils.actor.user.address.pending.cud',
154         $e->authtoken, $paddr);
155
156     if( $U->event_code($resp) ) {
157         $logger->error("Error updating pending address: $resp");
158         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
159     }
160
161     # in light of these changes, re-fetch latest data
162     $e->xact_begin; 
163     $self->prepare_extended_user_info;
164     $e->rollback;
165
166     return Apache2::Const::OK;
167 }
168
169 sub load_myopac_prefs_notify {
170     my $self = shift;
171     my $e = $self->editor;
172
173     my $user_prefs = $self->fetch_optin_prefs;
174     $user_prefs = $self->update_optin_prefs($user_prefs)
175         if $self->cgi->request_method eq 'POST';
176
177     $self->ctx->{opt_in_settings} = $user_prefs; 
178
179     return Apache2::Const::OK;
180 }
181
182 sub fetch_optin_prefs {
183     my $self = shift;
184     my $e = $self->editor;
185
186     # fetch all of the opt-in settings the user has access to
187     # XXX: user's should in theory have options to opt-in to notices
188     # for remote locations, but that opens the door for a large
189     # set of generally un-used opt-ins.. needs discussion
190     my $opt_ins =  $U->simplereq(
191         'open-ils.actor',
192         'open-ils.actor.event_def.opt_in.settings.atomic',
193         $e->authtoken, $e->requestor->home_ou);
194
195     # some opt-ins are staff-only
196     $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
197
198     # fetch user setting values for each of the opt-in settings
199     my $user_set = $U->simplereq(
200         'open-ils.actor',
201         'open-ils.actor.patron.settings.retrieve',
202         $e->authtoken, 
203         $e->requestor->id, 
204         [map {$_->name} @$opt_ins]
205     );
206
207     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
208 }
209
210 sub update_optin_prefs {
211     my $self = shift;
212     my $user_prefs = shift;
213     my $e = $self->editor;
214     my @settings = $self->cgi->param('setting');
215     my %newsets;
216
217     # apply now-true settings
218     for my $applied (@settings) {
219         # see if setting is already applied to this user
220         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
221         $newsets{$applied} = OpenSRF::Utils::JSON->true;
222     }
223
224     # remove now-false settings
225     for my $pref (grep { $_->{value} } @$user_prefs) {
226         $newsets{$pref->{cust}->name} = undef 
227             unless grep { $_ eq $pref->{cust}->name } @settings;
228     }
229
230     $U->simplereq(
231         'open-ils.actor',
232         'open-ils.actor.patron.settings.update',
233         $e->authtoken, $e->requestor->id, \%newsets);
234
235     # update the local prefs to match reality
236     for my $pref (@$user_prefs) {
237         $pref->{value} = $newsets{$pref->{cust}->name} 
238             if exists $newsets{$pref->{cust}->name};
239     }
240
241     return $user_prefs;
242 }
243
244 sub _load_user_with_prefs {
245     my $self = shift;
246     my $stat = $self->prepare_extended_user_info('settings');
247     return $stat if $stat; # not-OK
248
249     $self->ctx->{user_setting_map} = {
250         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
251             @{$self->ctx->{user}->settings}
252     };
253
254     return undef;
255 }
256
257 sub _get_bookbag_sort_params {
258     my ($self, $param_name) = @_;
259
260     # The interface that feeds this cgi parameter will provide a single
261     # argument for a QP sort filter, and potentially a modifier after a period.
262     # In practice this means the "sort" parameter will be something like
263     # "titlesort" or "authorsort.descending".
264     my $sorter = $self->cgi->param($param_name) || "";
265     my $modifier;
266     if ($sorter) {
267         $sorter =~ s/^(.*?)\.(.*)/$1/;
268         $modifier = $2 || undef;
269     }
270
271     return ($sorter, $modifier);
272 }
273
274 sub _prepare_bookbag_container_query {
275     my ($self, $container_id, $sorter, $modifier) = @_;
276
277     return sprintf(
278         "container(bre,bookbag,%d,%s)%s%s",
279         $container_id, $self->editor->authtoken,
280         ($sorter ? " sort($sorter)" : ""),
281         ($modifier ? "#$modifier" : "")
282     );
283 }
284
285 sub _prepare_anonlist_sorting_query {
286     my ($self, $list, $sorter, $modifier) = @_;
287
288     return sprintf(
289         "record_list(%s)%s%s",
290         join(",", @$list),
291         ($sorter ? " sort($sorter)" : ""),
292         ($modifier ? "#$modifier" : "")
293     );
294 }
295
296
297 sub load_myopac_prefs_settings {
298     my $self = shift;
299
300     my @user_prefs = qw/
301         opac.hits_per_page
302         opac.default_search_location
303     /;
304
305     my $stat = $self->_load_user_with_prefs;
306     return $stat if $stat;
307
308     return Apache2::Const::OK
309         unless $self->cgi->request_method eq 'POST';
310
311     # some setting values from the form don't match the 
312     # required value/format for the db, so they have to be 
313     # individually translated.
314
315     my %settings;
316     my $set_map = $self->ctx->{user_setting_map};
317
318     foreach my $key (@user_prefs) {
319         my $val = $self->cgi->param($key);
320         $settings{$key}= $val unless $$set_map{$key} eq $val;
321     }
322
323     my $now = DateTime->now->strftime('%F');
324     foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
325         my $val = $self->cgi->param($key);
326         if($val and $val eq 'on') {
327             # Set the start time to 'now' unless a start time already exists for the user
328             $settings{$key} = $now unless $$set_map{$key};
329         } else {
330             # clear the start time if one previously existed for the user
331             $settings{$key} = undef if $$set_map{$key};
332         }
333     }
334     
335     # Send the modified settings off to be saved
336     $U->simplereq(
337         'open-ils.actor', 
338         'open-ils.actor.patron.settings.update',
339         $self->editor->authtoken, undef, \%settings);
340
341     # re-fetch user prefs 
342     $self->ctx->{updated_user_settings} = \%settings;
343     return $self->_load_user_with_prefs || Apache2::Const::OK;
344 }
345
346 sub fetch_user_holds {
347     my $self = shift;
348     my $hold_ids = shift;
349     my $ids_only = shift;
350     my $flesh = shift;
351     my $available = shift;
352     my $limit = shift;
353     my $offset = shift;
354
355     my $e = $self->editor;
356
357     if(!$hold_ids) {
358         my $circ = OpenSRF::AppSession->create('open-ils.circ');
359
360         $hold_ids = $circ->request(
361             'open-ils.circ.holds.id_list.retrieve.authoritative', 
362             $e->authtoken, 
363             $e->requestor->id
364         )->gather(1);
365         $circ->kill_me;
366     
367         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
368     }
369
370
371     return $hold_ids if $ids_only or @$hold_ids == 0;
372
373     my $args = {
374         suppress_notices => 1,
375         suppress_transits => 1,
376         suppress_mvr => 1,
377         suppress_patron_details => 1
378     };
379
380     # ----------------------------------------------------------------
381     # Collect holds in batches of $batch_size for faster retrieval
382
383     my $batch_size = 8;
384     my $batch_idx = 0;
385     my $mk_req_batch = sub {
386         my @ses;
387         my $top_idx = $batch_idx + $batch_size;
388         while($batch_idx < $top_idx) {
389             my $hold_id = $hold_ids->[$batch_idx++];
390             last unless $hold_id;
391             my $ses = OpenSRF::AppSession->create('open-ils.circ');
392             my $req = $ses->request(
393                 'open-ils.circ.hold.details.retrieve', 
394                 $e->authtoken, $hold_id, $args);
395             push(@ses, {ses => $ses, req => $req});
396         }
397         return @ses;
398     };
399
400     my $first = 1;
401     my(@collected, @holds, @ses);
402
403     while(1) {
404         @ses = $mk_req_batch->() if $first;
405         last if $first and not @ses;
406
407         if(@collected) {
408             # If desired by the caller, filter any holds that are not available.
409             if ($available) {
410                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
411             }
412             while(my $blob = pop(@collected)) {
413                 my (undef, @data) = $self->get_records_and_facets(
414                     [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
415                 );
416                 $blob->{marc_xml} = $data[0]->{marc_xml};
417                 push(@holds, $blob);
418             }
419         }
420
421         for my $req_data (@ses) {
422             push(@collected, {hold => $req_data->{req}->gather(1)});
423             $req_data->{ses}->kill_me;
424         }
425
426         @ses = $mk_req_batch->();
427         last unless @collected or @ses;
428         $first = 0;
429     }
430
431     # put the holds back into the original server sort order
432     my @sorted;
433     for my $id (@$hold_ids) {
434         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
435     }
436
437     return \@sorted;
438 }
439
440 sub handle_hold_update {
441     my $self = shift;
442     my $action = shift;
443     my $hold_ids = shift;
444     my $e = $self->editor;
445     my $url;
446
447     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
448     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
449
450     my $circ = OpenSRF::AppSession->create('open-ils.circ');
451
452     if($action =~ /cancel/) {
453
454         for my $hold_id (@hold_ids) {
455             my $resp = $circ->request(
456                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
457         }
458
459     } elsif ($action =~ /activate|suspend/) {
460         
461         my $vlist = [];
462         for my $hold_id (@hold_ids) {
463             my $vals = {id => $hold_id};
464
465             if($action =~ /activate/) {
466                 $vals->{frozen} = 'f';
467                 $vals->{thaw_date} = undef;
468
469             } elsif($action =~ /suspend/) {
470                 $vals->{frozen} = 't';
471                 # $vals->{thaw_date} = TODO;
472             }
473             push(@$vlist, $vals);
474         }
475
476         my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
477         $self->ctx->{hold_suspend_post_capture} = 1 if 
478             grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
479
480     } elsif ($action eq 'edit') {
481
482         my @vals = map {
483             my $val = {"id" => $_};
484             $val->{"frozen"} = $self->cgi->param("frozen");
485             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
486
487             for my $field (qw/expire_time thaw_date/) {
488                 # XXX TODO make this support other date formats, not just
489                 # MM/DD/YYYY.
490                 next unless $self->cgi->param($field) =~
491                     m:^(\d{2})/(\d{2})/(\d{4})$:;
492                 $val->{$field} = "$3-$1-$2";
493             }
494             $val;
495         } @hold_ids;
496
497         $circ->request(
498             'open-ils.circ.hold.update.batch.atomic',
499             $e->authtoken, undef, \@vals
500         )->gather(1);   # LFW XXX test for failure
501         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
502     }
503
504     $circ->kill_me;
505     return defined($url) ? $self->generic_redirect($url) : undef;
506 }
507
508 sub load_myopac_holds {
509     my $self = shift;
510     my $e = $self->editor;
511     my $ctx = $self->ctx;
512     
513     my $limit = $self->cgi->param('limit') || 0;
514     my $offset = $self->cgi->param('offset') || 0;
515     my $action = $self->cgi->param('action') || '';
516     my $hold_id = $self->cgi->param('id');
517     my $available = int($self->cgi->param('available') || 0);
518
519     my $hold_handle_result;
520     $hold_handle_result = $self->handle_hold_update($action) if $action;
521
522     $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
523
524     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
525 }
526
527 sub load_place_hold {
528     my $self = shift;
529     my $ctx = $self->ctx;
530     my $gos = $ctx->{get_org_setting};
531     my $e = $self->editor;
532     my $cgi = $self->cgi;
533
534     $self->ctx->{page} = 'place_hold';
535     my @targets = $cgi->param('hold_target');
536     my @parts = $cgi->param('part');
537
538     $ctx->{hold_type} = $cgi->param('hold_type');
539     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
540
541     return $self->generic_redirect unless @targets;
542
543     $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
544
545     # if the staff client provides a patron barcode, fetch the patron
546     if (my $bc = $self->cgi->cookie("patron_barcode")) {
547         $ctx->{patron_recipient} = $U->simplereq(
548             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
549             $self->editor->authtoken, $bc
550         ) or return Apache2::Const::HTTP_BAD_REQUEST;
551
552         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
553     }
554
555     my $request_lib = $e->requestor->ws_ou;
556     my @hold_data;
557     $ctx->{hold_data} = \@hold_data;
558
559     my $type_dispatch = {
560         T => sub {
561             my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
562
563             for my $id (@targets) { # force back into the correct order
564                 my ($rec) = grep {$_->id eq $id} @$recs;
565
566                 # NOTE: if tpac ever supports locked-down pickup libs,
567                 # we'll need to pass a pickup_lib param along with the 
568                 # record to filter the set of monographic parts.
569                 my $parts = $U->simplereq(
570                     'open-ils.search',
571                     'open-ils.search.biblio.record_hold_parts', 
572                     {record => $rec->id}
573                 );
574
575                 # T holds on records that have parts are OK, but if the record has 
576                 # no non-part copies, the hold will ultimately fail.  When that 
577                 # happens, require the user to select a part.
578                 my $part_required = 0;
579                 if (@$parts) {
580                     my $np_copies = $e->json_query({
581                         select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]}, 
582                         from => {acp => {acn => {}, acpm => {type => 'left'}}}, 
583                         where => {
584                             '+acp' => {deleted => 'f'},
585                             '+acn' => {deleted => 'f', record => $rec->id}, 
586                             '+acpm' => {id => undef}
587                         }
588                     });
589                     $part_required = 1 if $np_copies->[0]->{count} == 0;
590                 }
591
592                 push(@hold_data, {
593                     target => $rec, 
594                     record => $rec,
595                     parts => $parts,
596                     part_required => $part_required
597                 });
598             }
599         },
600         V => sub {
601             my $vols = $e->batch_retrieve_asset_call_number([
602                 \@targets, {
603                     "flesh" => 1,
604                     "flesh_fields" => {"acn" => ["record"]}
605                 }
606             ], {substream => 1});
607
608             for my $id (@targets) { 
609                 my ($vol) = grep {$_->id eq $id} @$vols;
610                 push(@hold_data, {target => $vol, record => $vol->record});
611             }
612         },
613         C => sub {
614             my $copies = $e->batch_retrieve_asset_copy([
615                 \@targets, {
616                     "flesh" => 2,
617                     "flesh_fields" => {
618                         "acn" => ["record"],
619                         "acp" => ["call_number"]
620                     }
621                 }
622             ], {substream => 1});
623
624             for my $id (@targets) { 
625                 my ($copy) = grep {$_->id eq $id} @$copies;
626                 push(@hold_data, {target => $copy, record => $copy->call_number->record});
627             }
628         },
629         I => sub {
630             my $isses = $e->batch_retrieve_serial_issuance([
631                 \@targets, {
632                     "flesh" => 2,
633                     "flesh_fields" => {
634                         "siss" => ["subscription"], "ssub" => ["record_entry"]
635                     }
636                 }
637             ], {substream => 1});
638
639             for my $id (@targets) { 
640                 my ($iss) = grep {$_->id eq $id} @$isses;
641                 push(@hold_data, {target => $iss, record => $iss->subscription->record_entry});
642             }
643         }
644         # ...
645
646     }->{$ctx->{hold_type}}->();
647
648     # caller sent bad target IDs or the wrong hold type
649     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
650
651     # generate the MARC xml for each record
652     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
653
654     my $pickup_lib = $cgi->param('pickup_lib');
655     # no pickup lib means no holds placement
656     return Apache2::Const::OK unless $pickup_lib;
657
658     $ctx->{hold_attempt_made} = 1;
659
660     # Give the original CGI params back to the user in case they
661     # want to try to override something.
662     $ctx->{orig_params} = $cgi->Vars;
663     delete $ctx->{orig_params}{submit};
664     delete $ctx->{orig_params}{hold_target};
665     delete $ctx->{orig_params}{part};
666
667     my $usr = $e->requestor->id;
668
669     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
670         # find the real hold target
671
672         $usr = $U->simplereq(
673             'open-ils.actor', 
674             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
675             $e->authtoken, $cgi->param("hold_usr"));
676
677         if (defined $U->event_code($usr)) {
678             $ctx->{hold_failed} = 1;
679             $ctx->{hold_failed_event} = $usr;
680         }
681     }
682
683     # target_id is the true target_id for holds placement.  
684     # needed for attempt_hold_placement()
685     # With the exception of P-type holds, target_id == target->id.
686     $_->{target_id} = $_->{target}->id for @hold_data;
687
688     if ($ctx->{hold_type} eq 'T') {
689
690         # Much like quantum wave-particles, P-type holds pop into 
691         # and out of existence at the user's whim.  For our purposes,
692         # we treat such holds as T(itle) holds with a selected_part 
693         # designation.  When the time comes to pass the hold information 
694         # off for holds possibility testing and placement, make it look 
695         # like a real P-type hold.
696         my (@p_holds, @t_holds);
697         
698         for my $idx (0..$#parts) {
699             my $hdata = $hold_data[$idx];
700             if (my $part = $parts[$idx]) {
701                 $hdata->{target_id} = $part;
702                 $hdata->{selected_part} = $part;
703                 push(@p_holds, $hdata);
704             } else {
705                 push(@t_holds, $hdata);
706             }
707         }
708
709         $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
710         $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
711
712     } else {
713         $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
714     }
715
716     # NOTE: we are leaving the staff-placed patron barcode cookie 
717     # in place.  Otherwise, it's not possible to place more than 
718     # one hold for the patron within a staff/patron session.  This 
719     # does leave the barcode to linger longer than is ideal, but 
720     # normal staff work flow will cause the cookie to be replaced 
721     # with each new patron anyway.
722     # TODO: See about getting the staff client to clear the cookie
723
724     # return to the place_hold page so the results of the hold
725     # placement attempt can be reported to the user
726     return Apache2::Const::OK;
727 }
728
729 sub attempt_hold_placement {
730     my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
731     my $cgi = $self->cgi;
732     my $ctx = $self->ctx;
733     my $e = $self->editor;
734
735     # First see if we should warn/block for any holds that 
736     # might have locally available items.
737     for my $hdata (@hold_data) {
738         my ($local_block, $local_alert) = $self->local_avail_concern(
739             $hdata->{target_id}, $hold_type, $pickup_lib);
740     
741         if ($local_block) {
742             $hdata->{hold_failed} = 1;
743             $hdata->{hold_local_block} = 1;
744         } elsif ($local_alert) {
745             $hdata->{hold_failed} = 1;
746             $hdata->{hold_local_alert} = 1;
747         }
748     }
749
750     my $method = 'open-ils.circ.holds.test_and_create.batch';
751     $method .= '.override' if $cgi->param('override');
752
753     my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
754
755     if(@create_targets) {
756
757         my $bses = OpenSRF::AppSession->create('open-ils.circ');
758         my $breq = $bses->request( 
759             $method, 
760             $e->authtoken, 
761             {   patronid => $usr, 
762                 pickup_lib => $pickup_lib, 
763                 hold_type => $hold_type
764             }, 
765             \@create_targets
766         );
767
768         while (my $resp = $breq->recv) {
769
770             $resp = $resp->content;
771             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
772
773             if ($U->event_code($resp)) {
774                 $ctx->{general_hold_error} = $resp;
775                 last;
776             }
777
778             my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
779             my $result = $resp->{result};
780
781             if ($U->event_code($result)) {
782                 # e.g. permission denied
783                 $hdata->{hold_failed} = 1;
784                 $hdata->{hold_failed_event} = $result;
785
786             } else {
787                 
788                 if(not ref $result and $result > 0) {
789                     # successul hold returns the hold ID
790
791                     $hdata->{hold_success} = $result; 
792     
793                 } else {
794                     # hold-specific failure event 
795                     $hdata->{hold_failed} = 1;
796
797                     if (ref $result eq 'HASH') {
798                         $hdata->{hold_failed_event} = $result->{last_event};
799                     } elsif (ref $result eq 'ARRAY') {
800                         $hdata->{hold_failed_event} = pop @$result;
801                     }
802
803                     $hdata->{could_override} = $self->test_could_override($hdata->{hold_failed_event});
804                 }
805             }
806         }
807
808         $bses->kill_me;
809     }
810 }
811
812 sub fetch_user_circs {
813     my $self = shift;
814     my $flesh = shift; # flesh bib data, etc.
815     my $circ_ids = shift;
816     my $limit = shift;
817     my $offset = shift;
818
819     my $e = $self->editor;
820
821     my @circ_ids;
822
823     if($circ_ids) {
824         @circ_ids = @$circ_ids;
825
826     } else {
827
828         my $query = {
829             select => {circ => ['id']},
830             from => 'circ',
831             where => {
832                 '+circ' => {
833                     usr => $e->requestor->id,
834                     checkin_time => undef,
835                     '-or' => [
836                         {stop_fines => undef},
837                         {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
838                     ],
839                 }
840             },
841             order_by => {circ => ['due_date']}
842         };
843
844         $query->{limit} = $limit if $limit;
845         $query->{offset} = $offset if $offset;
846
847         my $ids = $e->json_query($query);
848         @circ_ids = map {$_->{id}} @$ids;
849     }
850
851     return [] unless @circ_ids;
852
853     my $qflesh = {
854         flesh => 3,
855         flesh_fields => {
856             circ => ['target_copy'],
857             acp => ['call_number'],
858             acn => ['record']
859         }
860     };
861
862     $e->xact_begin;
863     my $circs = $e->search_action_circulation(
864         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
865
866     my @circs;
867     for my $circ (@$circs) {
868         push(@circs, {
869             circ => $circ, 
870             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
871                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
872                 undef  # pre-cat copy, use the dummy title/author instead
873         });
874     }
875     $e->xact_rollback;
876
877     # make sure the final list is in the correct order
878     my @sorted_circs;
879     for my $id (@circ_ids) {
880         push(
881             @sorted_circs,
882             (grep { $_->{circ}->id == $id } @circs)
883         );
884     }
885
886     return \@sorted_circs;
887 }
888
889
890 sub handle_circ_renew {
891     my $self = shift;
892     my $action = shift;
893     my $ctx = $self->ctx;
894
895     my @renew_ids = $self->cgi->param('circ');
896
897     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
898
899     # TODO: fire off renewal calls in batches to speed things up
900     my @responses;
901     for my $circ (@$circs) {
902
903         my $evt = $U->simplereq(
904             'open-ils.circ', 
905             'open-ils.circ.renew',
906             $self->editor->authtoken,
907             {
908                 patron_id => $self->editor->requestor->id,
909                 copy_id => $circ->{circ}->target_copy,
910                 opac_renewal => 1
911             }
912         );
913
914         # TODO return these, then insert them into the circ data 
915         # blob that is shoved into the template for each circ
916         # so the template won't have to match them
917         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
918     }
919
920     return @responses;
921 }
922
923
924 sub load_myopac_circs {
925     my $self = shift;
926     my $e = $self->editor;
927     my $ctx = $self->ctx;
928
929     $ctx->{circs} = [];
930     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
931     my $offset = $self->cgi->param('offset') || 0;
932     my $action = $self->cgi->param('action') || '';
933
934     # perform the renewal first if necessary
935     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
936
937     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
938
939     my $success_renewals = 0;
940     my $failed_renewals = 0;
941     for my $data (@{$ctx->{circs}}) {
942         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
943
944         if($resp) {
945             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
946             $data->{renewal_response} = $evt;
947             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
948             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
949         }
950     }
951
952     $ctx->{success_renewals} = $success_renewals;
953     $ctx->{failed_renewals} = $failed_renewals;
954
955     return Apache2::Const::OK;
956 }
957
958 sub load_myopac_circ_history {
959     my $self = shift;
960     my $e = $self->editor;
961     my $ctx = $self->ctx;
962     my $limit = $self->cgi->param('limit') || 15;
963     my $offset = $self->cgi->param('offset') || 0;
964
965     $ctx->{circ_history_limit} = $limit;
966     $ctx->{circ_history_offset} = $offset;
967
968     my $circ_ids = $e->json_query({
969         select => {
970             au => [{
971                 column => 'id', 
972                 transform => 'action.usr_visible_circs', 
973                 result_field => 'id'
974             }]
975         },
976         from => 'au',
977         where => {id => $e->requestor->id}, 
978         limit => $limit,
979         offset => $offset
980     });
981
982     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
983     return Apache2::Const::OK;
984 }
985
986 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
987 sub load_myopac_hold_history {
988     my $self = shift;
989     my $e = $self->editor;
990     my $ctx = $self->ctx;
991     my $limit = $self->cgi->param('limit') || 15;
992     my $offset = $self->cgi->param('offset') || 0;
993     $ctx->{hold_history_limit} = $limit;
994     $ctx->{hold_history_offset} = $offset;
995
996     my $hold_ids = $e->json_query({
997         select => {
998             au => [{
999                 column => 'id', 
1000                 transform => 'action.usr_visible_holds', 
1001                 result_field => 'id'
1002             }]
1003         },
1004         from => 'au',
1005         where => {id => $e->requestor->id}, 
1006         limit => $limit,
1007         offset => $offset
1008     });
1009
1010     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
1011     return Apache2::Const::OK;
1012 }
1013
1014 sub load_myopac_payment_form {
1015     my $self = shift;
1016     my $r;
1017
1018     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1019     $r = $self->prepare_extended_user_info and return $r;
1020
1021     return Apache2::Const::OK;
1022 }
1023
1024 # TODO: add other filter options as params/configs/etc.
1025 sub load_myopac_payments {
1026     my $self = shift;
1027     my $limit = $self->cgi->param('limit') || 20;
1028     my $offset = $self->cgi->param('offset') || 0;
1029     my $e = $self->editor;
1030
1031     $self->ctx->{payment_history_limit} = $limit;
1032     $self->ctx->{payment_history_offset} = $offset;
1033
1034     my $args = {};
1035     $args->{limit} = $limit if $limit;
1036     $args->{offset} = $offset if $offset;
1037
1038     if (my $max_age = $self->ctx->{get_org_setting}->(
1039         $e->requestor->home_ou, "opac.payment_history_age_limit"
1040     )) {
1041         my $min_ts = DateTime->now(
1042             "time_zone" => DateTime::TimeZone->new("name" => "local"),
1043         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1044         
1045         $logger->info("XXX min_ts: $min_ts");
1046         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1047     }
1048
1049     $self->ctx->{payments} = $U->simplereq(
1050         'open-ils.actor',
1051         'open-ils.actor.user.payments.retrieve.atomic',
1052         $e->authtoken, $e->requestor->id, $args);
1053
1054     return Apache2::Const::OK;
1055 }
1056
1057 sub load_myopac_pay {
1058     my $self = shift;
1059     my $r;
1060
1061     my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1062     $logger->info("tpac paying fines for xacts @payment_xacts");
1063
1064     $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1065
1066     # balance_owed is computed specifically from the fines we're trying
1067     # to pay in this case.
1068     if ($self->ctx->{fines}->{balance_owed} <= 0) {
1069         $self->apache->log->info(
1070             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
1071                 join(", ", map(int, $self->cgi->param("xact"), $self->cgi->param('xact_misc'))))
1072         );
1073         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1074     }
1075
1076     my $cc_args = {"where_process" => 1};
1077
1078     $cc_args->{$_} = $self->cgi->param($_) for (qw/
1079         number cvv2 expire_year expire_month billing_first
1080         billing_last billing_address billing_city billing_state
1081         billing_zip
1082     /);
1083
1084     my $args = {
1085         "cc_args" => $cc_args,
1086         "userid" => $self->ctx->{user}->id,
1087         "payment_type" => "credit_card_payment",
1088         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
1089     };
1090
1091     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1092         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1093     );
1094
1095     $self->ctx->{"payment_response"} = $resp;
1096
1097     unless ($resp->{"textcode"}) {
1098         $self->ctx->{printable_receipt} = $U->simplereq(
1099            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1100            $self->editor->authtoken, $resp->{payments}
1101         );
1102     }
1103
1104     return Apache2::Const::OK;
1105 }
1106
1107 sub load_myopac_receipt_print {
1108     my $self = shift;
1109
1110     $self->ctx->{printable_receipt} = $U->simplereq(
1111        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1112        $self->editor->authtoken, [$self->cgi->param("payment")]
1113     );
1114
1115     return Apache2::Const::OK;
1116 }
1117
1118 sub load_myopac_receipt_email {
1119     my $self = shift;
1120
1121     # The following ML method doesn't actually check whether the user in
1122     # question has an email address, so we do.
1123     if ($self->ctx->{user}->email) {
1124         $self->ctx->{email_receipt_result} = $U->simplereq(
1125            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1126            $self->editor->authtoken, [$self->cgi->param("payment")]
1127         );
1128     } else {
1129         $self->ctx->{email_receipt_result} =
1130             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1131     }
1132
1133     return Apache2::Const::OK;
1134 }
1135
1136 sub prepare_fines {
1137     my ($self, $limit, $offset, $id_list) = @_;
1138
1139     # XXX TODO: check for failure after various network calls
1140
1141     # It may be unclear, but this result structure lumps circulation and
1142     # reservation fines together, and keeps grocery fines separate.
1143     $self->ctx->{"fines"} = {
1144         "circulation" => [],
1145         "grocery" => [],
1146         "total_paid" => 0,
1147         "total_owed" => 0,
1148         "balance_owed" => 0
1149     };
1150
1151     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1152
1153     # TODO: This should really be a ML call, but the existing calls 
1154     # return an excessive amount of data and don't offer streaming
1155
1156     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1157
1158     my $req = $cstore->request(
1159         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1160         {
1161             usr => $self->editor->requestor->id,
1162             balance_owed => {'!=' => 0},
1163             ($id_list && @$id_list ? ("id" => $id_list) : ()),
1164         },
1165         {
1166             flesh => 4,
1167             flesh_fields => {
1168                 mobts => [qw/grocery circulation reservation/],
1169                 bresv => ['target_resource_type'],
1170                 brt => ['record'],
1171                 mg => ['billings'],
1172                 mb => ['btype'],
1173                 circ => ['target_copy'],
1174                 acp => ['call_number'],
1175                 acn => ['record']
1176             },
1177             order_by => { mobts => 'xact_start' },
1178             %paging
1179         }
1180     );
1181
1182     my @total_keys = qw/total_paid total_owed balance_owed/;
1183     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1184
1185     while(my $resp = $req->recv) {
1186         my $mobts = $resp->content;
1187         my $circ = $mobts->circulation;
1188
1189         my $last_billing;
1190         if($mobts->grocery) {
1191             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1192             $last_billing = pop(@billings);
1193         }
1194
1195         # XXX TODO confirm that the following, and the later division by 100.0
1196         # to get a floating point representation once again, is sufficiently
1197         # "money-safe" math.
1198         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1199
1200         my $marc_xml = undef;
1201         if ($mobts->xact_type eq 'reservation' and
1202             $mobts->reservation->target_resource_type->record) {
1203             $marc_xml = XML::LibXML->new->parse_string(
1204                 $mobts->reservation->target_resource_type->record->marc
1205             );
1206         } elsif ($mobts->xact_type eq 'circulation' and
1207             $circ->target_copy->call_number->id != -1) {
1208             $marc_xml = XML::LibXML->new->parse_string(
1209                 $circ->target_copy->call_number->record->marc
1210             );
1211         }
1212
1213         push(
1214             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1215             {
1216                 xact => $mobts,
1217                 last_grocery_billing => $last_billing,
1218                 marc_xml => $marc_xml
1219             } 
1220         );
1221     }
1222
1223     $cstore->kill_me;
1224
1225     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1226     return;
1227 }
1228
1229 sub prepare_fines_for_payment {
1230     # This assumes $self->prepare_fines has already been run
1231     my ($self) = @_;
1232
1233     my @results = ();
1234     if ($self->ctx->{fines}) {
1235         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1236             @{$self->ctx->{fines}->{circulation}},
1237             @{$self->ctx->{fines}->{grocery}}
1238         );
1239     }
1240
1241     return \@results;
1242 }
1243
1244 sub load_myopac_main {
1245     my $self = shift;
1246     my $limit = $self->cgi->param('limit') || 0;
1247     my $offset = $self->cgi->param('offset') || 0;
1248     $self->ctx->{search_ou} = $self->_get_search_lib();
1249
1250     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1251 }
1252
1253 sub load_myopac_update_email {
1254     my $self = shift;
1255     my $e = $self->editor;
1256     my $ctx = $self->ctx;
1257     my $email = $self->cgi->param('email') || '';
1258     my $current_pw = $self->cgi->param('current_pw') || '';
1259
1260     # needed for most up-to-date email address
1261     if (my $r = $self->prepare_extended_user_info) { return $r };
1262
1263     return Apache2::Const::OK 
1264         unless $self->cgi->request_method eq 'POST';
1265
1266     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1267         $ctx->{invalid_email} = $email;
1268         return Apache2::Const::OK;
1269     }
1270
1271     my $stat = $U->simplereq(
1272         'open-ils.actor', 
1273         'open-ils.actor.user.email.update', 
1274         $e->authtoken, $email, $current_pw);
1275
1276     if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1277         $ctx->{password_incorrect} = 1;
1278         return Apache2::Const::OK;
1279     }
1280
1281     unless ($self->cgi->param("redirect_to")) {
1282         my $url = $self->apache->unparsed_uri;
1283         $url =~ s/update_email/prefs/;
1284
1285         return $self->generic_redirect($url);
1286     }
1287
1288     return $self->generic_redirect;
1289 }
1290
1291 sub load_myopac_update_username {
1292     my $self = shift;
1293     my $e = $self->editor;
1294     my $ctx = $self->ctx;
1295     my $username = $self->cgi->param('username') || '';
1296     my $current_pw = $self->cgi->param('current_pw') || '';
1297
1298     $self->prepare_extended_user_info;
1299
1300     my $allow_change = 1;
1301     my $regex_check;
1302     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1303     if($lock_usernames == 1) {
1304         # Policy says no username changes
1305         $allow_change = 0;
1306     } else {
1307         # We want this further down.
1308         $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1309         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1310         if($username_unlimit != 1) {
1311             if(!$regex_check) {
1312                 # Default is "starts with a number"
1313                 $regex_check = '^\d+';
1314             }
1315             # You already have a username?
1316             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1317                 $allow_change = 0;
1318             }
1319         }
1320     }
1321     if(!$allow_change) {
1322         my $url = $self->apache->unparsed_uri;
1323         $url =~ s/update_username/prefs/;
1324
1325         return $self->generic_redirect($url);
1326     }
1327
1328     return Apache2::Const::OK 
1329         unless $self->cgi->request_method eq 'POST';
1330
1331     unless($username and $username !~ /\s/) { # any other username restrictions?
1332         $ctx->{invalid_username} = $username;
1333         return Apache2::Const::OK;
1334     }
1335
1336     # New username can't look like a barcode if we have a barcode regex
1337     if($regex_check and $username =~ /$regex_check/) {
1338         $ctx->{invalid_username} = $username;
1339         return Apache2::Const::OK;
1340     }
1341
1342     # New username has to look like a username if we have a username regex
1343     $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1344     if($regex_check and $username !~ /$regex_check/) {
1345         $ctx->{invalid_username} = $username;
1346         return Apache2::Const::OK;
1347     }
1348
1349     if($username ne $e->requestor->usrname) {
1350
1351         my $evt = $U->simplereq(
1352             'open-ils.actor', 
1353             'open-ils.actor.user.username.update', 
1354             $e->authtoken, $username, $current_pw);
1355
1356         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1357             $ctx->{password_incorrect} = 1;
1358             return Apache2::Const::OK;
1359         }
1360
1361         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1362             $ctx->{username_exists} = $username;
1363             return Apache2::Const::OK;
1364         }
1365     }
1366
1367     my $url = $self->apache->unparsed_uri;
1368     $url =~ s/update_username/prefs/;
1369
1370     return $self->generic_redirect($url);
1371 }
1372
1373 sub load_myopac_update_password {
1374     my $self = shift;
1375     my $e = $self->editor;
1376     my $ctx = $self->ctx;
1377
1378     return Apache2::Const::OK 
1379         unless $self->cgi->request_method eq 'POST';
1380
1381     my $current_pw = $self->cgi->param('current_pw') || '';
1382     my $new_pw = $self->cgi->param('new_pw') || '';
1383     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1384
1385     unless($new_pw eq $new_pw2) {
1386         $ctx->{password_nomatch} = 1;
1387         return Apache2::Const::OK;
1388     }
1389
1390     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1391
1392     if(!$pw_regex) {
1393         # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1394         $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1395     }
1396
1397     if($pw_regex and $new_pw !~ /$pw_regex/) {
1398         $ctx->{password_invalid} = 1;
1399         return Apache2::Const::OK;
1400     }
1401
1402     my $evt = $U->simplereq(
1403         'open-ils.actor', 
1404         'open-ils.actor.user.password.update', 
1405         $e->authtoken, $new_pw, $current_pw);
1406
1407
1408     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1409         $ctx->{password_incorrect} = 1;
1410         return Apache2::Const::OK;
1411     }
1412
1413     my $url = $self->apache->unparsed_uri;
1414     $url =~ s/update_password/prefs/;
1415
1416     return $self->generic_redirect($url);
1417 }
1418
1419 sub _update_bookbag_metadata {
1420     my ($self, $bookbag) = @_;
1421
1422     $bookbag->name($self->cgi->param("name"));
1423     $bookbag->description($self->cgi->param("description"));
1424
1425     return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1426     return 0;
1427 }
1428
1429 sub load_myopac_bookbags {
1430     my $self = shift;
1431     my $e = $self->editor;
1432     my $ctx = $self->ctx;
1433
1434     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1435     $e->xact_begin; # replication...
1436
1437     my $rv = $self->load_mylist;
1438     unless($rv eq Apache2::Const::OK) {
1439         $e->rollback;
1440         return $rv;
1441     }
1442
1443     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1444         [
1445             {owner => $e->requestor->id, btype => 'bookbag'}, {
1446                 order_by => {cbreb => 'name'},
1447                 limit => $self->cgi->param('limit') || 10,
1448                 offset => $self->cgi->param('offset') || 0
1449             }
1450         ],
1451         {substream => 1}
1452     );
1453
1454     if(!$ctx->{bookbags}) {
1455         $e->rollback;
1456         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1457     }
1458     
1459     # If the user wants a specific bookbag's items, load them.
1460     # XXX add bookbag item paging support
1461
1462     if ($self->cgi->param("id")) {
1463         my ($bookbag) =
1464             grep { $_->id eq $self->cgi->param("id") } @{$ctx->{bookbags}};
1465
1466         if (!$bookbag) {
1467             $e->rollback;
1468             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1469         }
1470
1471         if ($self->cgi->param("action") eq "editmeta") {
1472             if (!$self->_update_bookbag_metadata($bookbag))  {
1473                 $e->rollback;
1474                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1475             } else {
1476                 $e->commit;
1477                 my $url = $self->ctx->{opac_root} . '/myopac/lists?id=' .
1478                     $bookbag->id;
1479
1480                 # Keep it if we've got it
1481                 if ($self->cgi->param("sort")) {
1482                     $url .= ";sort=" . $self->cgi->param("sort");
1483                 }
1484
1485                 return $self->generic_redirect($url);
1486             }
1487         }
1488
1489         my $query = $self->_prepare_bookbag_container_query(
1490             $bookbag->id, $sorter, $modifier
1491         );
1492
1493         # XXX we need to limit the number of records per bbag; use third arg
1494         # of bib_container_items_via_search() i think.
1495         my $items = $U->bib_container_items_via_search($bookbag->id, $query)
1496             or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1497
1498         my (undef, @recs) = $self->get_records_and_facets(
1499             [ map {$_->target_biblio_record_entry->id} @$items ],
1500             undef, 
1501             {flesh => '{mra}'}
1502         );
1503
1504         $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1505
1506         $bookbag->items($items);
1507     }
1508
1509     $e->rollback;
1510     return Apache2::Const::OK;
1511 }
1512
1513
1514 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1515 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1516 sub load_myopac_bookbag_update {
1517     my ($self, $action, $list_id, @hold_recs) = @_;
1518     my $e = $self->editor;
1519     my $cgi = $self->cgi;
1520
1521     # save_notes is effectively another action, but is passed in a separate
1522     # CGI parameter for what are really just layout reasons.
1523     $action = 'save_notes' if $cgi->param('save_notes');
1524     $action ||= $cgi->param('action');
1525
1526     $list_id ||= $cgi->param('list');
1527
1528     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1529     my @selected_item = $cgi->param('selected_item');
1530     my $shared = $cgi->param('shared');
1531     my $name = $cgi->param('name');
1532     my $description = $cgi->param('description');
1533     my $success = 0;
1534     my $list;
1535
1536     # This url intentionally leaves off the edit_notes parameter, but
1537     # may need to add some back in for paging.
1538
1539     my $url = "https://" . $self->apache->hostname .
1540         $self->ctx->{opac_root} . "/myopac/lists?";
1541
1542     $url .= 'sort=' . uri_escape($cgi->param("sort")) if $cgi->param("sort");
1543
1544     if ($action eq 'create') {
1545         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1546         $list->name($name);
1547         $list->description($description);
1548         $list->owner($e->requestor->id);
1549         $list->btype('bookbag');
1550         $list->pub($shared ? 't' : 'f');
1551         $success = $U->simplereq('open-ils.actor', 
1552             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1553
1554     } elsif($action eq 'place_hold') {
1555
1556         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1557         unless (@hold_recs) {
1558             if (@selected_item) {
1559                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1560                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1561             }
1562         }
1563                 
1564         return Apache2::Const::OK unless @hold_recs;
1565         $logger->info("placing holds from list page on: @hold_recs");
1566
1567         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1568         $url .= ';hold_target=' . $_ for @hold_recs;
1569         return $self->generic_redirect($url);
1570
1571     } else {
1572
1573         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1574
1575         return Apache2::Const::HTTP_BAD_REQUEST unless 
1576             $list and $list->owner == $e->requestor->id;
1577     }
1578
1579     if($action eq 'delete') {
1580         $success = $U->simplereq('open-ils.actor', 
1581             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1582
1583     } elsif($action eq 'show') {
1584         unless($U->is_true($list->pub)) {
1585             $list->pub('t');
1586             $success = $U->simplereq('open-ils.actor', 
1587                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1588         }
1589
1590     } elsif($action eq 'hide') {
1591         if($U->is_true($list->pub)) {
1592             $list->pub('f');
1593             $success = $U->simplereq('open-ils.actor', 
1594                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1595         }
1596
1597     } elsif($action eq 'rename') {
1598         if($name) {
1599             $list->name($name);
1600             $success = $U->simplereq('open-ils.actor', 
1601                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1602         }
1603
1604     } elsif($action eq 'add_rec') {
1605         foreach my $add_rec (@add_rec) {
1606             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1607             $item->bucket($list_id);
1608             $item->target_biblio_record_entry($add_rec);
1609             $success = $U->simplereq('open-ils.actor', 
1610                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1611             last unless $success;
1612         }
1613
1614     } elsif($action eq 'del_item') {
1615         foreach (@selected_item) {
1616             $success = $U->simplereq(
1617                 'open-ils.actor',
1618                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1619             );
1620             last unless $success;
1621         }
1622     } elsif ($action eq 'save_notes') {
1623         $success = $self->update_bookbag_item_notes;
1624         $url .= "&id=" . uri_escape($cgi->param("id")) if $cgi->param("id");
1625     }
1626
1627     return $self->generic_redirect($url) if $success;
1628
1629     # XXX FIXME Bucket failure doesn't have a page to show the user anything
1630     # right now. User just sees a 404 currently.
1631
1632     $self->ctx->{bucket_action} = $action;
1633     $self->ctx->{bucket_action_failed} = 1;
1634     return Apache2::Const::OK;
1635 }
1636
1637 sub update_bookbag_item_notes {
1638     my ($self) = @_;
1639     my $e = $self->editor;
1640
1641     my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
1642     my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
1643
1644     # We're going to leverage an API call that's already been written to check
1645     # permissions appropriately.
1646
1647     my $a = create OpenSRF::AppSession("open-ils.actor");
1648     my $method = "open-ils.actor.container.item_note.cud";
1649
1650     for my $note_key (@note_keys) {
1651         my $note;
1652
1653         my $id = ($note_key =~ /(\d+)/)[0];
1654
1655         if (!($note =
1656             $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
1657             my $event = $e->die_event;
1658             $self->apache->log->warn(
1659                 "error retrieving cbrebin id $id, got event " .
1660                 $event->{textcode}
1661             );
1662             $a->kill_me;
1663             $self->ctx->{bucket_action_event} = $event;
1664             return;
1665         }
1666
1667         if (length($self->cgi->param($note_key))) {
1668             $note->ischanged(1);
1669             $note->note($self->cgi->param($note_key));
1670         } else {
1671             $note->isdeleted(1);
1672         }
1673
1674         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1675
1676         if (defined $U->event_code($r)) {
1677             $self->apache->log->warn(
1678                 "attempt to modify cbrebin " . $note->id .
1679                 " returned event " .  $r->{textcode}
1680             );
1681             $e->rollback;
1682             $a->kill_me;
1683             $self->ctx->{bucket_action_event} = $r;
1684             return;
1685         }
1686     }
1687
1688     for my $item_key (@item_keys) {
1689         my $id = int(($item_key =~ /(\d+)/)[0]);
1690         my $text = $self->cgi->param($item_key);
1691
1692         chomp $text;
1693         next unless length $text;
1694
1695         my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
1696         $note->isnew(1);
1697         $note->item($id);
1698         $note->note($text);
1699
1700         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
1701
1702         if (defined $U->event_code($r)) {
1703             $self->apache->log->warn(
1704                 "attempt to create cbrebin for item " . $note->item .
1705                 " returned event " .  $r->{textcode}
1706             );
1707             $e->rollback;
1708             $a->kill_me;
1709             $self->ctx->{bucket_action_event} = $r;
1710             return;
1711         }
1712     }
1713
1714     $a->kill_me;
1715     return 1;   # success
1716 }
1717
1718 sub load_myopac_bookbag_print {
1719     my ($self) = @_;
1720
1721     $self->apache->content_type("text/plain; encoding=utf8");
1722
1723     my $id = int($self->cgi->param("list"));
1724
1725     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1726
1727     my $item_search =
1728         $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
1729
1730     my $bbag;
1731
1732     # Get the bookbag object itself, assuming we're allowed to.
1733     if ($self->editor->allowed("VIEW_CONTAINER")) {
1734
1735         $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1736     } else {
1737         my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
1738             {
1739                 "id" => $id,
1740                 "-or" => {
1741                     "owner" => $self->editor->requestor->id,
1742                     "pub" => "t"
1743                 }
1744             }
1745         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1746
1747         $bbag = pop @$bookbags;
1748     }
1749
1750     # If we have a bookbag we're allowed to look at, issue the A/T event
1751     # to get CSV, passing as a user param that search query we built before.
1752     if ($bbag) {
1753         $self->ctx->{csv} = $U->fire_object_event(
1754             undef, "container.biblio_record_entry_bucket.csv",
1755             $bbag, $self->editor->requestor->home_ou,
1756             undef, {"item_search" => $item_search}
1757         );
1758     }
1759
1760     # Create a reasonable filename and set the content disposition to
1761     # provoke browser download dialogs.
1762     (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
1763
1764     $self->apache->headers_out->add(
1765         "Content-Disposition",
1766         "attachment;filename=$filename.csv"
1767     );
1768
1769     return Apache2::Const::OK;
1770 }
1771
1772 sub load_password_reset {
1773     my $self = shift;
1774     my $cgi = $self->cgi;
1775     my $ctx = $self->ctx;
1776     my $barcode = $cgi->param('barcode');
1777     my $username = $cgi->param('username');
1778     my $email = $cgi->param('email');
1779     my $pwd1 = $cgi->param('pwd1');
1780     my $pwd2 = $cgi->param('pwd2');
1781     my $uuid = $ctx->{page_args}->[0];
1782
1783     if ($uuid) {
1784
1785         $logger->info("patron password reset with uuid $uuid");
1786
1787         if ($pwd1 and $pwd2) {
1788
1789             if ($pwd1 eq $pwd2) {
1790
1791                 my $response = $U->simplereq(
1792                     'open-ils.actor', 
1793                     'open-ils.actor.patron.password_reset.commit',
1794                     $uuid, $pwd1);
1795
1796                 $logger->info("patron password reset response " . Dumper($response));
1797
1798                 if ($U->event_code($response)) { # non-success event
1799                     
1800                     my $code = $response->{textcode};
1801                     
1802                     if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
1803                         $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
1804                     }
1805
1806                     if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
1807                         $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
1808                     }
1809
1810                 } else { # success
1811
1812                     $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
1813                 }
1814
1815             } else { # passwords not equal
1816
1817                 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
1818             }
1819
1820         } else { # 2 password values needed
1821
1822             $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
1823         }
1824
1825     } elsif ($barcode or $username) {
1826
1827         my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
1828         push(@params, $email) if $email;
1829
1830         $U->simplereq(
1831             'open-ils.actor', 
1832             'open-ils.actor.patron.password_reset.request', @params);
1833
1834         $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
1835     }
1836
1837     $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
1838     return Apache2::Const::OK;
1839 }
1840
1841 1;