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