]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
LP#1194860: You have permission to override some of the failed holds. appearing when...
[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 OpenSRF::Utils::Cache;
11 use Digest::MD5 qw(md5_hex);
12 use Data::Dumper;
13 $Data::Dumper::Indent = 0;
14 use DateTime;
15 my $U = 'OpenILS::Application::AppUtils';
16
17 sub prepare_extended_user_info {
18     my $self = shift;
19     my @extra_flesh = @_;
20     my $e = $self->editor;
21
22     # are we already in a transaction?
23     my $local_xact = !$e->{xact_id}; 
24     $e->xact_begin if $local_xact;
25
26     # keep the original user object so we can restore
27     # login-specific data (e.g. workstation)
28     my $usr = $self->ctx->{user};
29
30     $self->ctx->{user} = $self->editor->retrieve_actor_user([
31         $self->ctx->{user}->id,
32         {
33             flesh => 1,
34             flesh_fields => {
35                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
36                 # ...
37             }
38         }
39     ]);
40
41     $e->rollback if $local_xact;
42
43     $self->ctx->{user}->wsid($usr->wsid);
44     $self->ctx->{user}->ws_ou($usr->ws_ou);
45
46     # discard replaced (negative-id) addresses.
47     $self->ctx->{user}->addresses([
48         grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
49
50     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR 
51         unless $self->ctx->{user};
52
53     return;
54 }
55
56 # Given an event returned by a failed attempt to create a hold, do we have
57 # permission to override?  XXX Should the permission check be scoped to a
58 # given org_unit context?
59 sub test_could_override {
60     my ($self, $event) = @_;
61
62     return 0 unless $event;
63     return 1 if $self->editor->allowed($event->{textcode} . ".override");
64     return 1 if $event->{"fail_part"} and
65         $self->editor->allowed($event->{"fail_part"} . ".override");
66     return 0;
67 }
68
69 # Find out whether we care that local copies are available
70 sub local_avail_concern {
71     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
72
73     my $would_block = $self->ctx->{get_org_setting}->
74         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
75     my $would_alert = (
76         $self->ctx->{get_org_setting}->
77             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
78                 not $self->cgi->param("override")
79     ) unless $would_block;
80
81     if ($would_block or $would_alert) {
82         my $args = {
83             "hold_target" => $hold_target,
84             "hold_type" => $hold_type,
85             "org_unit" => $pickup_lib
86         };
87         my $local_avail = $U->simplereq(
88             "open-ils.circ",
89             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
90         );
91         $logger->info(
92             "copy availability information for " . Dumper($args) .
93             " is " . Dumper($local_avail)
94         );
95         if (%$local_avail) { # if hash not empty
96             $self->ctx->{hold_copy_available} = $local_avail;
97             return ($would_block, $would_alert);
98         }
99     }
100
101     return (0, 0);
102 }
103
104 # context additions: 
105 #   user : au object, fleshed
106 sub load_myopac_prefs {
107     my $self = shift;
108     my $cgi = $self->cgi;
109     my $e = $self->editor;
110     my $pending_addr = $cgi->param('pending_addr');
111     my $replace_addr = $cgi->param('replace_addr');
112     my $delete_pending = $cgi->param('delete_pending');
113
114     $self->prepare_extended_user_info;
115     my $user = $self->ctx->{user};
116
117     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
118     if(defined($lock_usernames) and $lock_usernames == 1) {
119         # Policy says no username changes
120         $self->ctx->{username_change_disallowed} = 1;
121     } else {
122         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
123         if(!$username_unlimit) {
124             my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
125             if(!$regex_check) {
126                 # Default is "starts with a number"
127                 $regex_check = '^\d+';
128             }
129             # You already have a username?
130             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
131                 $self->ctx->{username_change_disallowed} = 1;
132             }
133         }
134     }
135
136     return Apache2::Const::OK unless 
137         $pending_addr or $replace_addr or $delete_pending;
138
139     my @form_fields = qw/address_type street1 street2 city county state country post_code/;
140
141     my $paddr;
142     if( $pending_addr ) { # update an existing pending address
143
144         ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
145         return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
146         $paddr->$_( $cgi->param($_) ) for @form_fields;
147
148     } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
149
150         $paddr = Fieldmapper::actor::user_address->new;
151         $paddr->isnew(1);
152         $paddr->usr($user->id);
153         $paddr->pending('t');
154         $paddr->replaces($replace_addr);
155         $paddr->$_( $cgi->param($_) ) for @form_fields;
156
157     } elsif( $delete_pending ) {
158         $paddr = $e->retrieve_actor_user_address($delete_pending);
159         return Apache2::Const::HTTP_BAD_REQUEST unless 
160             $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
161         $paddr->isdeleted(1);
162     }
163
164     my $resp = $U->simplereq(
165         'open-ils.actor', 
166         'open-ils.actor.user.address.pending.cud',
167         $e->authtoken, $paddr);
168
169     if( $U->event_code($resp) ) {
170         $logger->error("Error updating pending address: $resp");
171         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
172     }
173
174     # in light of these changes, re-fetch latest data
175     $e->xact_begin; 
176     $self->prepare_extended_user_info;
177     $e->rollback;
178
179     return Apache2::Const::OK;
180 }
181
182 sub load_myopac_prefs_notify {
183     my $self = shift;
184     my $e = $self->editor;
185
186
187     my $stat = $self->_load_user_with_prefs;
188     return $stat if $stat;
189
190     my $user_prefs = $self->fetch_optin_prefs;
191     $user_prefs = $self->update_optin_prefs($user_prefs)
192         if $self->cgi->request_method eq 'POST';
193
194     $self->ctx->{opt_in_settings} = $user_prefs;
195
196     return Apache2::Const::OK
197         unless $self->cgi->request_method eq 'POST';
198
199     my %settings;
200     my $set_map = $self->ctx->{user_setting_map};
201  
202     foreach my $key (qw/
203         opac.default_phone
204         opac.default_sms_notify
205     /) {
206         my $val = $self->cgi->param($key);
207         $settings{$key}= $val unless $$set_map{$key} eq $val;
208     }
209
210     my $key = 'opac.default_sms_carrier';
211     my $val = $self->cgi->param('sms_carrier');
212     $settings{$key}= $val unless $$set_map{$key} eq $val;
213
214     $key = 'opac.hold_notify';
215     my @notify_methods = ();
216     if ($self->cgi->param($key . ".email") eq 'on') {
217         push @notify_methods, "email";
218     }
219     if ($self->cgi->param($key . ".phone") eq 'on') {
220         push @notify_methods, "phone";
221     }
222     if ($self->cgi->param($key . ".sms") eq 'on') {
223         push @notify_methods, "sms";
224     }
225     $val = join("|",@notify_methods);
226     $settings{$key}= $val unless $$set_map{$key} eq $val;
227
228     # Send the modified settings off to be saved
229     $U->simplereq(
230         'open-ils.actor', 
231         'open-ils.actor.patron.settings.update',
232         $self->editor->authtoken, undef, \%settings);
233
234     # re-fetch user prefs 
235     $self->ctx->{updated_user_settings} = \%settings;
236     return $self->_load_user_with_prefs || Apache2::Const::OK;
237 }
238
239 sub fetch_optin_prefs {
240     my $self = shift;
241     my $e = $self->editor;
242
243     # fetch all of the opt-in settings the user has access to
244     # XXX: user's should in theory have options to opt-in to notices
245     # for remote locations, but that opens the door for a large
246     # set of generally un-used opt-ins.. needs discussion
247     my $opt_ins =  $U->simplereq(
248         'open-ils.actor',
249         'open-ils.actor.event_def.opt_in.settings.atomic',
250         $e->authtoken, $e->requestor->home_ou);
251
252     # some opt-ins are staff-only
253     $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
254
255     # fetch user setting values for each of the opt-in settings
256     my $user_set = $U->simplereq(
257         'open-ils.actor',
258         'open-ils.actor.patron.settings.retrieve',
259         $e->authtoken, 
260         $e->requestor->id, 
261         [map {$_->name} @$opt_ins]
262     );
263
264     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
265 }
266
267 sub load_myopac_messages {
268     my $self = shift;
269     my $e = $self->editor;
270     my $ctx = $self->ctx;
271     my $cgi = $self->cgi;
272
273     my $limit  = $cgi->param('limit') || 20;
274     my $offset = $cgi->param('offset') || 0;
275
276     my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
277     $pcrud->connect();
278
279     my $action = $cgi->param('action') || '';
280     if ($action) {
281         my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
282         if ($changed > 0 || $failed > 0) {
283             $ctx->{message_update_action} = $action;
284             $ctx->{message_update_changed} = $changed;
285             $ctx->{message_update_failed} = $failed;
286             $self->update_dashboard_stats();
287         }
288     }
289
290     my $single = $cgi->param('single') || 0;
291     my $id = $cgi->param('message_id');
292
293     my $messages;
294     my $fetch_all = 1;
295     if (!$action && $single && $id) {
296         $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
297         if (scalar(@$messages) == 1) {
298             $ctx->{display_single_message} = 1;
299             $ctx->{patron_message_id} = $id;
300             $fetch_all = 0;
301         }
302     }
303
304     if ($fetch_all) {
305         # fetch all the messages
306         ($ctx->{patron_messages_count}, $messages) =
307             $self->_fetch_user_messages($pcrud, $offset, $limit);    
308     }
309
310     $pcrud->kill_me;
311
312     foreach my $aum (@$messages) {
313
314         push @{ $ctx->{patron_messages} }, {
315             id          => $aum->id,
316             title       => $aum->title,
317             message     => $aum->message,
318             create_date => $aum->create_date,
319             is_read     => defined($aum->read_date) ? 1 : 0,
320             library     => $aum->sending_lib->name, 
321         };
322     }
323
324     $ctx->{patron_messages_limit} = $limit;
325     $ctx->{patron_messages_offset} = $offset;
326
327     return Apache2::Const::OK;
328 }
329
330 sub _fetch_and_mark_read_single_message {
331     my $self = shift;
332     my $pcrud = shift;
333     my $id = shift;
334
335     $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
336     my $messages = $pcrud->request(
337         'open-ils.pcrud.search.auml.atomic',
338         $self->editor->authtoken,
339         {
340             usr     => $self->editor->requestor->id,
341             deleted => 'f',
342             id      => $id,
343         },
344         {
345             flesh => 1,
346             flesh_fields => { auml => ['sending_lib'] },
347         }
348     )->gather(1);
349     if (@$messages) {
350         $messages->[0]->read_date('now');
351         $pcrud->request(
352             'open-ils.pcrud.update.auml',
353             $self->editor->authtoken,
354             $messages->[0]
355         )->gather(1);
356     }
357     $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
358
359     $self->update_dashboard_stats();
360
361     return $messages;
362 }
363
364 sub _fetch_user_messages {
365     my $self = shift;
366     my $pcrud = shift;
367     my $offset = shift;
368     my $limit = shift;
369
370     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
371
372     my $all_messages = $pcrud->request(
373         'open-ils.pcrud.id_list.auml.atomic',
374         $self->editor->authtoken,
375         {
376             usr     => $self->editor->requestor->id,
377             deleted => 'f'
378         },
379         {}
380     )->gather(1);
381
382     my $messages = $pcrud->request(
383         'open-ils.pcrud.search.auml.atomic',
384         $self->editor->authtoken,
385         {
386             usr     => $self->editor->requestor->id,
387             deleted => 'f'
388         },
389         {
390             flesh => 1,
391             flesh_fields => { auml => ['sending_lib'] },
392             order_by => { auml => 'create_date DESC' },
393             %paging
394         }
395     )->gather(1);
396
397     return scalar(@$all_messages), $messages;
398 }
399
400 sub _handle_message_action {
401     my $self = shift;
402     my $pcrud = shift;
403     my $action = shift;
404     my $cgi = $self->cgi;
405
406     my @ids = $cgi->param('message_id');
407     return (0, 0) unless @ids;
408
409     my $changed = 0;
410     my $failed = 0;
411     $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
412     for my $id (@ids) {
413         my $aum = $pcrud->request(
414             'open-ils.pcrud.retrieve.auml',
415             $self->editor->authtoken,
416             $id
417         )->gather(1);
418         next unless $aum;
419         if      ($action eq 'mark_read') {
420             $aum->read_date('now');
421         } elsif ($action eq 'mark_unread') {
422             $aum->clear_read_date();
423         } elsif ($action eq 'mark_deleted') {
424             $aum->deleted('t');
425         }
426         $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
427             $changed++ :
428             $failed++;
429     }
430     if ($failed) {
431         $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
432         $changed = 0;
433         $failed = scalar(@ids);
434     } else {
435         $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
436     }
437     return ($changed, $failed);
438 }
439
440 sub _load_lists_and_settings {
441     my $self = shift;
442     my $e = $self->editor;
443     my $stat = $self->_load_user_with_prefs;
444     unless ($stat) {
445         my $exclude = 0;
446         my $setting_map = $self->ctx->{user_setting_map};
447         $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
448         $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
449             [
450                 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
451                     order_by => {cbreb => 'name'},
452                     limit => $self->cgi->param('limit') || 10,
453                     offset => $self->cgi->param('offset') || 0
454                 }
455             ]
456         );
457         # We also want a total count of the user's bookbags.
458         my $q = {
459             'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
460             'from' => 'cbreb',
461             'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
462         };
463         my $r = $e->json_query($q);
464         $self->ctx->{bookbag_count} = $r->[0]->{'count'};
465         # Someone has requested that we use the default list's name
466         # rather than "Default List."
467         if ($exclude) {
468             $q = {
469                 'select' => {'cbreb' => ['name']},
470                 'from' => 'cbreb',
471                 'where' => {'id' => $exclude}
472             };
473             $r = $e->json_query($q);
474             $self->ctx->{default_bookbag} = $r->[0]->{'name'};
475         }
476     } else {
477         return $stat;
478     }
479     return undef;
480 }
481
482 sub update_optin_prefs {
483     my $self = shift;
484     my $user_prefs = shift;
485     my $e = $self->editor;
486     my @settings = $self->cgi->param('setting');
487     my %newsets;
488
489     # apply now-true settings
490     for my $applied (@settings) {
491         # see if setting is already applied to this user
492         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
493         $newsets{$applied} = OpenSRF::Utils::JSON->true;
494     }
495
496     # remove now-false settings
497     for my $pref (grep { $_->{value} } @$user_prefs) {
498         $newsets{$pref->{cust}->name} = undef 
499             unless grep { $_ eq $pref->{cust}->name } @settings;
500     }
501
502     $U->simplereq(
503         'open-ils.actor',
504         'open-ils.actor.patron.settings.update',
505         $e->authtoken, $e->requestor->id, \%newsets);
506
507     # update the local prefs to match reality
508     for my $pref (@$user_prefs) {
509         $pref->{value} = $newsets{$pref->{cust}->name} 
510             if exists $newsets{$pref->{cust}->name};
511     }
512
513     return $user_prefs;
514 }
515
516 sub _load_user_with_prefs {
517     my $self = shift;
518     my $stat = $self->prepare_extended_user_info('settings');
519     return $stat if $stat; # not-OK
520
521     $self->ctx->{user_setting_map} = {
522         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
523             @{$self->ctx->{user}->settings}
524     };
525
526     return undef;
527 }
528
529 sub _get_bookbag_sort_params {
530     my ($self, $param_name) = @_;
531
532     # The interface that feeds this cgi parameter will provide a single
533     # argument for a QP sort filter, and potentially a modifier after a period.
534     # In practice this means the "sort" parameter will be something like
535     # "titlesort" or "authorsort.descending".
536     my $sorter = $self->cgi->param($param_name) || "";
537     my $modifier;
538     if ($sorter) {
539         $sorter =~ s/^(.*?)\.(.*)/$1/;
540         $modifier = $2 || undef;
541     }
542
543     return ($sorter, $modifier);
544 }
545
546 sub _prepare_bookbag_container_query {
547     my ($self, $container_id, $sorter, $modifier) = @_;
548
549     return sprintf(
550         "container(bre,bookbag,%d,%s)%s%s",
551         $container_id, $self->editor->authtoken,
552         ($sorter ? " sort($sorter)" : ""),
553         ($modifier ? "#$modifier" : "")
554     );
555 }
556
557 sub _prepare_anonlist_sorting_query {
558     my ($self, $list, $sorter, $modifier) = @_;
559
560     return sprintf(
561         "record_list(%s)%s%s",
562         join(",", @$list),
563         ($sorter ? " sort($sorter)" : ""),
564         ($modifier ? "#$modifier" : "")
565     );
566 }
567
568
569 sub load_myopac_prefs_settings {
570     my $self = shift;
571
572     my @user_prefs = qw/
573         opac.hits_per_page
574         opac.default_search_location
575         opac.default_pickup_location
576         opac.temporary_list_no_warn
577     /;
578
579     my $stat = $self->_load_user_with_prefs;
580     return $stat if $stat;
581
582     # if behind-desk holds are supported and the user
583     # setting which controls the value is opac-visible,
584     # add the setting to the list of settings to manage.
585     # note: this logic may need to be changed later to
586     # check whether behind-the-desk holds are supported
587     # anywhere the patron may select as a pickup lib.
588     my $e = $self->editor;
589     my $bdous = $self->ctx->{get_org_setting}->(
590         $e->requestor->home_ou,
591         'circ.holds.behind_desk_pickup_supported');
592
593     if ($bdous) {
594         my $setting = 
595             $e->retrieve_config_usr_setting_type(
596                 'circ.holds_behind_desk');
597
598         if ($U->is_true($setting->opac_visible)) {
599             push(@user_prefs, 'circ.holds_behind_desk');
600             $self->ctx->{behind_desk_supported} = 1;
601         }
602     }
603
604     return Apache2::Const::OK
605         unless $self->cgi->request_method eq 'POST';
606
607     # some setting values from the form don't match the 
608     # required value/format for the db, so they have to be 
609     # individually translated.
610
611     my %settings;
612     my $set_map = $self->ctx->{user_setting_map};
613
614     foreach my $key (@user_prefs) {
615         my $val = $self->cgi->param($key);
616         $settings{$key}= $val unless $$set_map{$key} eq $val;
617     }
618
619     my $now = DateTime->now->strftime('%F');
620     foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
621         my $val = $self->cgi->param($key);
622         if($val and $val eq 'on') {
623             # Set the start time to 'now' unless a start time already exists for the user
624             $settings{$key} = $now unless $$set_map{$key};
625         } else {
626             # clear the start time if one previously existed for the user
627             $settings{$key} = undef if $$set_map{$key};
628         }
629     }
630
631     # Send the modified settings off to be saved
632     $U->simplereq(
633         'open-ils.actor', 
634         'open-ils.actor.patron.settings.update',
635         $self->editor->authtoken, undef, \%settings);
636
637     # re-fetch user prefs 
638     $self->ctx->{updated_user_settings} = \%settings;
639     return $self->_load_user_with_prefs || Apache2::Const::OK;
640 }
641
642 sub load_myopac_prefs_my_lists {
643     my $self = shift;
644
645     my @user_prefs = qw/
646         opac.lists_per_page
647         opac.list_items_per_page
648     /;
649
650     my $stat = $self->_load_user_with_prefs;
651     return $stat if $stat;
652
653     return Apache2::Const::OK
654         unless $self->cgi->request_method eq 'POST';
655
656     my %settings;
657     my $set_map = $self->ctx->{user_setting_map};
658
659     foreach my $key (@user_prefs) {
660         my $val = $self->cgi->param($key);
661         $settings{$key}= $val unless $$set_map{$key} eq $val;
662     }
663
664     if (keys %settings) { # we found a different setting value
665         # Send the modified settings off to be saved
666         $U->simplereq(
667             'open-ils.actor',
668             'open-ils.actor.patron.settings.update',
669             $self->editor->authtoken, undef, \%settings);
670
671         # re-fetch user prefs
672         $self->ctx->{updated_user_settings} = \%settings;
673         $stat = $self->_load_user_with_prefs;
674     }
675
676     return $stat || Apache2::Const::OK;
677 }
678
679 sub fetch_user_holds {
680     my $self = shift;
681     my $hold_ids = shift;
682     my $ids_only = shift;
683     my $flesh = shift;
684     my $available = shift;
685     my $limit = shift;
686     my $offset = shift;
687
688     my $e = $self->editor;
689     my $all_ids; # to be used below.
690
691     if(!$hold_ids) {
692         my $circ = OpenSRF::AppSession->create('open-ils.circ');
693
694         $hold_ids = $circ->request(
695             'open-ils.circ.holds.id_list.retrieve.authoritative', 
696             $e->authtoken, 
697             $e->requestor->id,
698             $available
699         )->gather(1);
700         $circ->kill_me;
701
702         $all_ids = $hold_ids;
703         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
704
705     } else {
706         $all_ids = $hold_ids;
707     }
708
709     return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
710
711     my $args = {
712         suppress_notices => 1,
713         suppress_transits => 1,
714         suppress_mvr => 1,
715         suppress_patron_details => 1
716     };
717
718     # ----------------------------------------------------------------
719     # Collect holds in batches of $batch_size for faster retrieval
720
721     my $batch_size = 8;
722     my $batch_idx = 0;
723     my $mk_req_batch = sub {
724         my @ses;
725         my $top_idx = $batch_idx + $batch_size;
726         while($batch_idx < $top_idx) {
727             my $hold_id = $hold_ids->[$batch_idx++];
728             last unless $hold_id;
729             my $ses = OpenSRF::AppSession->create('open-ils.circ');
730             my $req = $ses->request(
731                 'open-ils.circ.hold.details.retrieve', 
732                 $e->authtoken, $hold_id, $args);
733             push(@ses, {ses => $ses, req => $req});
734         }
735         return @ses;
736     };
737
738     my $first = 1;
739     my(@collected, @holds, @ses);
740
741     while(1) {
742         @ses = $mk_req_batch->() if $first;
743         last if $first and not @ses;
744
745         if(@collected) {
746             while(my $blob = pop(@collected)) {
747                 my @data;
748
749                 # in the holds edit UI, we need to know what formats and
750                 # languages the user selected for this hold, plus what
751                 # formats/langs are available on the MR as a whole.
752                 if ($blob->{hold}{hold}->hold_type eq 'M') {
753                     my $hold = $blob->{hold}->{hold};
754
755                     # for MR, fetch the combined MR unapi blob
756                     (undef, @data) = $self->get_records_and_facets(
757                         [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
758
759                     my $filter_org = $U->org_unit_ancestor_at_depth(
760                         $hold->selection_ou,
761                         $hold->selection_depth);
762
763                     my $filter_data = $U->simplereq(
764                         'open-ils.circ',
765                         'open-ils.circ.mmr.holds.filters.authoritative.atomic', 
766                         $hold->target, $filter_org, [$hold->id]
767                     );
768
769                     $blob->{metarecord_filters} = 
770                         $filter_data->[0]->{metarecord};
771                     $blob->{metarecord_selected_filters} = 
772                         $filter_data->[1]->{hold};
773                 } else {
774
775                     (undef, @data) = $self->get_records_and_facets(
776                         [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
777                     );
778                 }
779
780                 $blob->{marc_xml} = $data[0]->{marc_xml};
781                 push(@holds, $blob);
782             }
783         }
784
785         for my $req_data (@ses) {
786             push(@collected, {hold => $req_data->{req}->gather(1)});
787             $req_data->{ses}->kill_me;
788         }
789
790         @ses = $mk_req_batch->();
791         last unless @collected or @ses;
792         $first = 0;
793     }
794
795     # put the holds back into the original server sort order
796     my @sorted;
797     for my $id (@$hold_ids) {
798         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
799     }
800
801     return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids };
802 }
803
804 sub handle_hold_update {
805     my $self = shift;
806     my $action = shift;
807     my $hold_ids = shift;
808     my $e = $self->editor;
809     my $url;
810
811     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
812     @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
813
814     my $circ = OpenSRF::AppSession->create('open-ils.circ');
815
816     if($action =~ /cancel/) {
817
818         for my $hold_id (@hold_ids) {
819             my $resp = $circ->request(
820                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
821         }
822
823     } elsif ($action =~ /activate|suspend/) {
824         
825         my $vlist = [];
826         for my $hold_id (@hold_ids) {
827             my $vals = {id => $hold_id};
828
829             if($action =~ /activate/) {
830                 $vals->{frozen} = 'f';
831                 $vals->{thaw_date} = undef;
832
833             } elsif($action =~ /suspend/) {
834                 $vals->{frozen} = 't';
835                 # $vals->{thaw_date} = TODO;
836             }
837             push(@$vlist, $vals);
838         }
839
840         my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
841         $self->ctx->{hold_suspend_post_capture} = 1 if 
842             grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
843
844     } elsif ($action eq 'edit') {
845
846         my @vals = map {
847             my $val = {"id" => $_};
848             $val->{"frozen"} = $self->cgi->param("frozen");
849             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
850
851             for my $field (qw/expire_time thaw_date/) {
852                 # XXX TODO make this support other date formats, not just
853                 # MM/DD/YYYY.
854                 next unless $self->cgi->param($field) =~
855                     m:^(\d{2})/(\d{2})/(\d{4})$:;
856                 $val->{$field} = "$3-$1-$2";
857             }
858
859             $val->{holdable_formats} = # no-op for non-MR holds
860                 $self->compile_holdable_formats(undef, $_);
861
862             $val;
863         } @hold_ids;
864
865         $circ->request(
866             'open-ils.circ.hold.update.batch.atomic',
867             $e->authtoken, undef, \@vals
868         )->gather(1);   # LFW XXX test for failure
869         $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
870         foreach my $param (('loc', 'qtype', 'query')) {
871             if ($self->cgi->param($param)) {
872                 $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
873             }
874         }
875     }
876
877     $circ->kill_me;
878     return defined($url) ? $self->generic_redirect($url) : undef;
879 }
880
881 sub load_myopac_holds {
882     my $self = shift;
883     my $e = $self->editor;
884     my $ctx = $self->ctx;
885     
886     my $limit = $self->cgi->param('limit') || 15;
887     my $offset = $self->cgi->param('offset') || 0;
888     my $action = $self->cgi->param('action') || '';
889     my $hold_id = $self->cgi->param('id');
890     my $available = int($self->cgi->param('available') || 0);
891
892     my $hold_handle_result;
893     $hold_handle_result = $self->handle_hold_update($action) if $action;
894
895     my $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
896     if($holds_object->{holds}) {
897         $ctx->{holds} = $holds_object->{holds};
898     }
899     $ctx->{holds_ids} = $holds_object->{all_ids};
900     $ctx->{holds_limit} = $limit;
901     $ctx->{holds_offset} = $offset;
902
903     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
904 }
905
906 my $data_filler;
907
908 sub load_place_hold {
909     my $self = shift;
910     my $ctx = $self->ctx;
911     my $gos = $ctx->{get_org_setting};
912     my $e = $self->editor;
913     my $cgi = $self->cgi;
914
915     $self->ctx->{page} = 'place_hold';
916     my @targets = $cgi->param('hold_target');
917     my @parts = $cgi->param('part');
918
919     $ctx->{hold_type} = $cgi->param('hold_type');
920     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
921     $ctx->{email_notify} = $cgi->param('email_notify');
922     if ($cgi->param('phone_notify_checkbox')) {
923         $ctx->{phone_notify} = $cgi->param('phone_notify');
924     }
925     if ($cgi->param('sms_notify_checkbox')) {
926         $ctx->{sms_notify} = $cgi->param('sms_notify');
927         $ctx->{sms_carrier} = $cgi->param('sms_carrier');
928     }
929
930     return $self->generic_redirect unless @targets;
931
932     $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
933
934     $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
935         $e->requestor->id,
936         {
937             flesh => 1,
938             flesh_fields => {
939                 au => ['settings', 'card']
940             }
941         }
942     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
943     my $user_setting_map = {
944         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
945             @{
946                 $ctx->{staff_recipient}->settings
947             }
948     };
949     $ctx->{user_setting_map} = $user_setting_map;
950
951     my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
952     if ($default_notify =~ /email/) {
953         $ctx->{default_email_notify} = 'checked';
954     } else {
955         $ctx->{default_email_notify} = '';
956     }
957     if ($default_notify =~ /phone/) {
958         $ctx->{default_phone_notify} = 'checked';
959     } else {
960         $ctx->{default_phone_notify} = '';
961     }
962     if ($default_notify =~ /sms/) {
963         $ctx->{default_sms_notify} = 'checked';
964     } else {
965         $ctx->{default_sms_notify} = '';
966     }
967
968     # If we have a default pickup location, grab it
969     if ($$user_setting_map{'opac.default_pickup_location'}) {
970         $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
971     }
972
973     my $request_lib = $e->requestor->ws_ou;
974     my @hold_data;
975     $ctx->{hold_data} = \@hold_data;
976
977     $data_filler = sub {
978         my $hdata = shift;
979         if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
980         if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
981         if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
982         if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
983         return $hdata;
984     };
985
986     my $type_dispatch = {
987         M => sub {
988             # target metarecords
989             my $mrecs = $e->batch_retrieve_metabib_metarecord([
990                 \@targets, 
991                 {flesh => 1, flesh_fields => {mmr => ['master_record']}}], 
992                 {substream => 1}
993             );
994
995             for my $id (@targets) {
996                 my ($mr) = grep {$_->id eq $id} @$mrecs;
997
998                 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
999                 my $filter_data = $U->simplereq(
1000                     'open-ils.circ',
1001                     'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1002
1003                 my $holdable_formats = 
1004                     $self->compile_holdable_formats($mr->id);
1005
1006                 push(@hold_data, $data_filler->({
1007                     target => $mr, 
1008                     record => $mr->master_record,
1009                     holdable_formats => $holdable_formats,
1010                     metarecord_filters => $filter_data->{metarecord}
1011                 }));
1012             }
1013         },
1014         T => sub {
1015             my $recs = $e->batch_retrieve_biblio_record_entry(
1016                 [\@targets,  {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1017                 {substream => 1}
1018             );
1019
1020             for my $id (@targets) { # force back into the correct order
1021                 my ($rec) = grep {$_->id eq $id} @$recs;
1022
1023                 # NOTE: if tpac ever supports locked-down pickup libs,
1024                 # we'll need to pass a pickup_lib param along with the 
1025                 # record to filter the set of monographic parts.
1026                 my $parts = $U->simplereq(
1027                     'open-ils.search',
1028                     'open-ils.search.biblio.record_hold_parts', 
1029                     {record => $rec->id}
1030                 );
1031
1032                 # T holds on records that have parts are OK, but if the record has 
1033                 # no non-part copies, the hold will ultimately fail.  When that 
1034                 # happens, require the user to select a part.
1035                 my $part_required = 0;
1036                 if (@$parts) {
1037                     my $np_copies = $e->json_query({
1038                         select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]}, 
1039                         from => {acp => {acn => {}, acpm => {type => 'left'}}}, 
1040                         where => {
1041                             '+acp' => {deleted => 'f'},
1042                             '+acn' => {deleted => 'f', record => $rec->id}, 
1043                             '+acpm' => {id => undef}
1044                         }
1045                     });
1046                     $part_required = 1 if $np_copies->[0]->{count} == 0;
1047                 }
1048
1049                 push(@hold_data, $data_filler->({
1050                     target => $rec,
1051                     record => $rec,
1052                     parts => $parts,
1053                     part_required => $part_required
1054                 }));
1055             }
1056         },
1057         V => sub {
1058             my $vols = $e->batch_retrieve_asset_call_number([
1059                 \@targets, {
1060                     "flesh" => 1,
1061                     "flesh_fields" => {"acn" => ["record"]}
1062                 }
1063             ], {substream => 1});
1064
1065             for my $id (@targets) { 
1066                 my ($vol) = grep {$_->id eq $id} @$vols;
1067                 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1068             }
1069         },
1070         C => sub {
1071             my $copies = $e->batch_retrieve_asset_copy([
1072                 \@targets, {
1073                     "flesh" => 2,
1074                     "flesh_fields" => {
1075                         "acn" => ["record"],
1076                         "acp" => ["call_number"]
1077                     }
1078                 }
1079             ], {substream => 1});
1080
1081             for my $id (@targets) { 
1082                 my ($copy) = grep {$_->id eq $id} @$copies;
1083                 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1084             }
1085         },
1086         I => sub {
1087             my $isses = $e->batch_retrieve_serial_issuance([
1088                 \@targets, {
1089                     "flesh" => 2,
1090                     "flesh_fields" => {
1091                         "siss" => ["subscription"], "ssub" => ["record_entry"]
1092                     }
1093                 }
1094             ], {substream => 1});
1095
1096             for my $id (@targets) { 
1097                 my ($iss) = grep {$_->id eq $id} @$isses;
1098                 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1099             }
1100         }
1101         # ...
1102
1103     }->{$ctx->{hold_type}}->();
1104
1105     # caller sent bad target IDs or the wrong hold type
1106     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1107
1108     # generate the MARC xml for each record
1109     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1110
1111     my $pickup_lib = $cgi->param('pickup_lib');
1112     # no pickup lib means no holds placement
1113     return Apache2::Const::OK unless $pickup_lib;
1114
1115     $ctx->{hold_attempt_made} = 1;
1116
1117     # Give the original CGI params back to the user in case they
1118     # want to try to override something.
1119     $ctx->{orig_params} = $cgi->Vars;
1120     delete $ctx->{orig_params}{submit};
1121     delete $ctx->{orig_params}{hold_target};
1122     delete $ctx->{orig_params}{part};
1123
1124     my $usr = $e->requestor->id;
1125
1126     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
1127         # find the real hold target
1128
1129         $usr = $U->simplereq(
1130             'open-ils.actor', 
1131             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1132             $e->authtoken, $cgi->param("hold_usr"));
1133
1134         if (defined $U->event_code($usr)) {
1135             $ctx->{hold_failed} = 1;
1136             $ctx->{hold_failed_event} = $usr;
1137         }
1138     }
1139
1140     # target_id is the true target_id for holds placement.  
1141     # needed for attempt_hold_placement()
1142     # With the exception of P-type holds, target_id == target->id.
1143     $_->{target_id} = $_->{target}->id for @hold_data;
1144
1145     if ($ctx->{hold_type} eq 'T') {
1146
1147         # Much like quantum wave-particles, P-type holds pop into 
1148         # and out of existence at the user's whim.  For our purposes,
1149         # we treat such holds as T(itle) holds with a selected_part 
1150         # designation.  When the time comes to pass the hold information 
1151         # off for holds possibility testing and placement, make it look 
1152         # like a real P-type hold.
1153         my (@p_holds, @t_holds);
1154         
1155         for my $idx (0..$#parts) {
1156             my $hdata = $hold_data[$idx];
1157             if (my $part = $parts[$idx]) {
1158                 $hdata->{target_id} = $part;
1159                 $hdata->{selected_part} = $part;
1160                 push(@p_holds, $hdata);
1161             } else {
1162                 push(@t_holds, $hdata);
1163             }
1164         }
1165
1166         $self->apache->log->warn("$#parts : @t_holds");
1167
1168         $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1169         $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1170
1171     } else {
1172         $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1173     }
1174
1175     # NOTE: we are leaving the staff-placed patron barcode cookie 
1176     # in place.  Otherwise, it's not possible to place more than 
1177     # one hold for the patron within a staff/patron session.  This 
1178     # does leave the barcode to linger longer than is ideal, but 
1179     # normal staff work flow will cause the cookie to be replaced 
1180     # with each new patron anyway.
1181     # TODO: See about getting the staff client to clear the cookie
1182
1183     # return to the place_hold page so the results of the hold
1184     # placement attempt can be reported to the user
1185     return Apache2::Const::OK;
1186 }
1187
1188 sub attempt_hold_placement {
1189     my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1190     my $cgi = $self->cgi;
1191     my $ctx = $self->ctx;
1192     my $e = $self->editor;
1193
1194     # First see if we should warn/block for any holds that 
1195     # might have locally available items.
1196     for my $hdata (@hold_data) {
1197         my ($local_block, $local_alert) = $self->local_avail_concern(
1198             $hdata->{target_id}, $hold_type, $pickup_lib);
1199     
1200         if ($local_block) {
1201             $hdata->{hold_failed} = 1;
1202             $hdata->{hold_local_block} = 1;
1203         } elsif ($local_alert) {
1204             $hdata->{hold_failed} = 1;
1205             $hdata->{hold_local_alert} = 1;
1206         }
1207     }
1208
1209     my $method = 'open-ils.circ.holds.test_and_create.batch';
1210
1211     if ($cgi->param('override')) {
1212         $method .= '.override';
1213
1214     } elsif (!$ctx->{is_staff})  {
1215
1216         $method .= '.override' if $self->ctx->{get_org_setting}->(
1217             $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1218     }
1219
1220     my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1221
1222     if(@create_targets) {
1223
1224         # holdable formats may be different for each MR hold.
1225         # map each set to the ID of the target.
1226         my $holdable_formats = {};
1227         if ($hold_type eq 'M') {
1228             $holdable_formats->{$_->{target_id}} = 
1229                 $_->{holdable_formats} for @hold_data;
1230         }
1231
1232         my $bses = OpenSRF::AppSession->create('open-ils.circ');
1233         my $breq = $bses->request( 
1234             $method, 
1235             $e->authtoken, 
1236             $data_filler->({   
1237                 patronid => $usr,
1238                 pickup_lib => $pickup_lib, 
1239                 hold_type => $hold_type,
1240                 holdable_formats_map => $holdable_formats
1241             }),
1242             \@create_targets
1243         );
1244
1245         while (my $resp = $breq->recv) {
1246
1247             $resp = $resp->content;
1248             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1249
1250             if ($U->event_code($resp)) {
1251                 $ctx->{general_hold_error} = $resp;
1252                 last;
1253             }
1254
1255             my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
1256             my $result = $resp->{result};
1257
1258             if ($U->event_code($result)) {
1259                 # e.g. permission denied
1260                 $hdata->{hold_failed} = 1;
1261                 $hdata->{hold_failed_event} = $result;
1262
1263             } else {
1264                 
1265                 if(not ref $result and $result > 0) {
1266                     # successul hold returns the hold ID
1267
1268                     $hdata->{hold_success} = $result; 
1269     
1270                 } else {
1271                     # hold-specific failure event 
1272                     $hdata->{hold_failed} = 1;
1273
1274                     if (ref $result eq 'HASH') {
1275                         $hdata->{hold_failed_event} = $result->{last_event};
1276
1277                         if ($result->{age_protected_copy}) {
1278                             my %temp = %{$hdata->{hold_failed_event}};
1279                             my $theTextcode = $temp{"textcode"};
1280                             $theTextcode.=".override";
1281                             $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1282                             $hdata->{age_protect} = 1;
1283                         } else {
1284                             $hdata->{could_override} = $result->{place_unfillable} || 
1285                                 $self->test_could_override($hdata->{hold_failed_event});
1286                         }
1287                     } elsif (ref $result eq 'ARRAY') {
1288                         $hdata->{hold_failed_event} = $result->[0];
1289
1290                         if ($result->[3]) { # age_protect_only
1291                             my %temp = %{$hdata->{hold_failed_event}};
1292                             my $theTextcode = $temp{"textcode"};
1293                             $theTextcode.=".override";
1294                             $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1295                             $hdata->{age_protect} = 1;
1296                         } else {
1297                             $hdata->{could_override} = $result->[4] || # place_unfillable
1298                                 $self->test_could_override($hdata->{hold_failed_event});
1299                         }
1300                     }
1301                 }
1302             }
1303         }
1304
1305         $bses->kill_me;
1306     }
1307 }
1308
1309 # pull the selected formats and languages for metarecord holds
1310 # from the CGI params and map them into the JSON holdable
1311 # formats...er, format.
1312 # if no metarecord is provided, we'll pull it from the target
1313 # of the provided hold.
1314 sub compile_holdable_formats {
1315     my ($self, $mr_id, $hold_id) = @_;
1316     my $e = $self->editor;
1317     my $cgi = $self->cgi;
1318
1319     # exit early if not needed
1320     return undef unless 
1321         grep /metarecord_formats_|metarecord_langs_/, 
1322         $cgi->param;
1323
1324     # CGI params are based on the MR id, since during hold placement
1325     # we have no old ID.  During hold edit, map the hold ID back to 
1326     # the metarecod target.
1327     $mr_id = 
1328         $e->retrieve_action_hold_request($hold_id)->target 
1329         unless $mr_id;
1330
1331     my $format_attr = $self->ctx->{get_cgf}->(
1332         'opac.metarecord.holds.format_attr');
1333
1334     if (!$format_attr) {
1335         $logger->error("Missing config.global_flag: ".
1336             "opac.metarecord.holds.format_attr!");
1337         return "";
1338     }
1339
1340     $format_attr = $format_attr->value;
1341
1342     # during hold placement or edit submission, the user selects
1343     # which of the available formats/langs are acceptable.
1344     # Capture those here as the holdable_formats for the MR hold.
1345     my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1346     my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1347
1348     # map the selected attrs into the JSON holdable_formats structure
1349     my $blob = {};
1350     if (@selected_formats) {
1351         $blob->{0} = [
1352             map { {_attr => $format_attr, _val => $_} } 
1353             @selected_formats
1354         ];
1355     }
1356     if (@selected_langs) {
1357         $blob->{1} = [
1358             map { {_attr => 'item_lang', _val => $_} } 
1359             @selected_langs
1360         ];
1361     }
1362
1363     return OpenSRF::Utils::JSON->perl2JSON($blob);
1364 }
1365
1366 sub fetch_user_circs {
1367     my $self = shift;
1368     my $flesh = shift; # flesh bib data, etc.
1369     my $circ_ids = shift;
1370     my $limit = shift;
1371     my $offset = shift;
1372
1373     my $e = $self->editor;
1374
1375     my @circ_ids;
1376
1377     if($circ_ids) {
1378         @circ_ids = @$circ_ids;
1379
1380     } else {
1381
1382         my $query = {
1383             select => {circ => ['id']},
1384             from => 'circ',
1385             where => {
1386                 '+circ' => {
1387                     usr => $e->requestor->id,
1388                     checkin_time => undef,
1389                     '-or' => [
1390                         {stop_fines => undef},
1391                         {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1392                     ],
1393                 }
1394             },
1395             order_by => {circ => ['due_date']}
1396         };
1397
1398         $query->{limit} = $limit if $limit;
1399         $query->{offset} = $offset if $offset;
1400
1401         my $ids = $e->json_query($query);
1402         @circ_ids = map {$_->{id}} @$ids;
1403     }
1404
1405     return [] unless @circ_ids;
1406
1407     my $qflesh = {
1408         flesh => 3,
1409         flesh_fields => {
1410             circ => ['target_copy'],
1411             acp => ['call_number'],
1412             acn => ['record']
1413         }
1414     };
1415
1416     $e->xact_begin;
1417     my $circs = $e->search_action_circulation(
1418         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1419
1420     my @circs;
1421     for my $circ (@$circs) {
1422         push(@circs, {
1423             circ => $circ, 
1424             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
1425                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
1426                 undef  # pre-cat copy, use the dummy title/author instead
1427         });
1428     }
1429     $e->rollback;
1430
1431     # make sure the final list is in the correct order
1432     my @sorted_circs;
1433     for my $id (@circ_ids) {
1434         push(
1435             @sorted_circs,
1436             (grep { $_->{circ}->id == $id } @circs)
1437         );
1438     }
1439
1440     return \@sorted_circs;
1441 }
1442
1443
1444 sub handle_circ_renew {
1445     my $self = shift;
1446     my $action = shift;
1447     my $ctx = $self->ctx;
1448
1449     my @renew_ids = $self->cgi->param('circ');
1450
1451     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1452
1453     # TODO: fire off renewal calls in batches to speed things up
1454     my @responses;
1455     for my $circ (@$circs) {
1456
1457         my $evt = $U->simplereq(
1458             'open-ils.circ', 
1459             'open-ils.circ.renew',
1460             $self->editor->authtoken,
1461             {
1462                 patron_id => $self->editor->requestor->id,
1463                 copy_id => $circ->{circ}->target_copy,
1464                 opac_renewal => 1
1465             }
1466         );
1467
1468         # TODO return these, then insert them into the circ data 
1469         # blob that is shoved into the template for each circ
1470         # so the template won't have to match them
1471         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1472     }
1473
1474     return @responses;
1475 }
1476
1477
1478 sub load_myopac_circs {
1479     my $self = shift;
1480     my $e = $self->editor;
1481     my $ctx = $self->ctx;
1482
1483     $ctx->{circs} = [];
1484     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1485     my $offset = $self->cgi->param('offset') || 0;
1486     my $action = $self->cgi->param('action') || '';
1487
1488     # perform the renewal first if necessary
1489     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1490
1491     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1492
1493     my $success_renewals = 0;
1494     my $failed_renewals = 0;
1495     for my $data (@{$ctx->{circs}}) {
1496         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1497
1498         if($resp) {
1499             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1500             $data->{renewal_response} = $evt;
1501             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1502             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1503         }
1504     }
1505
1506     $ctx->{success_renewals} = $success_renewals;
1507     $ctx->{failed_renewals} = $failed_renewals;
1508
1509     return Apache2::Const::OK;
1510 }
1511
1512 sub load_myopac_circ_history {
1513     my $self = shift;
1514     my $e = $self->editor;
1515     my $ctx = $self->ctx;
1516     my $limit = $self->cgi->param('limit') || 15;
1517     my $offset = $self->cgi->param('offset') || 0;
1518
1519     $ctx->{circ_history_limit} = $limit;
1520     $ctx->{circ_history_offset} = $offset;
1521
1522     my $circ_ids = $e->json_query({
1523         select => {
1524             au => [{
1525                 column => 'id', 
1526                 transform => 'action.usr_visible_circs', 
1527                 result_field => 'id'
1528             }]
1529         },
1530         from => 'au',
1531         where => {id => $e->requestor->id}, 
1532         limit => $limit,
1533         offset => $offset
1534     });
1535
1536     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1537     return Apache2::Const::OK;
1538 }
1539
1540 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
1541 sub load_myopac_hold_history {
1542     my $self = shift;
1543     my $e = $self->editor;
1544     my $ctx = $self->ctx;
1545     my $limit = $self->cgi->param('limit') || 15;
1546     my $offset = $self->cgi->param('offset') || 0;
1547     $ctx->{hold_history_limit} = $limit;
1548     $ctx->{hold_history_offset} = $offset;
1549
1550     my $hold_ids = $e->json_query({
1551         select => {
1552             au => [{
1553                 column => 'id', 
1554                 transform => 'action.usr_visible_holds', 
1555                 result_field => 'id'
1556             }]
1557         },
1558         from => 'au',
1559         where => {id => $e->requestor->id}
1560     });
1561
1562     my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1563     if($holds_object->{holds}) {
1564         $ctx->{holds} = $holds_object->{holds};
1565     }
1566     $ctx->{hold_history_ids} = $holds_object->{all_ids};
1567
1568     return Apache2::Const::OK;
1569 }
1570
1571 sub load_myopac_payment_form {
1572     my $self = shift;
1573     my $r;
1574
1575     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1576     $r = $self->prepare_extended_user_info and return $r;
1577
1578     return Apache2::Const::OK;
1579 }
1580
1581 # TODO: add other filter options as params/configs/etc.
1582 sub load_myopac_payments {
1583     my $self = shift;
1584     my $limit = $self->cgi->param('limit') || 20;
1585     my $offset = $self->cgi->param('offset') || 0;
1586     my $e = $self->editor;
1587
1588     $self->ctx->{payment_history_limit} = $limit;
1589     $self->ctx->{payment_history_offset} = $offset;
1590
1591     my $args = {};
1592     $args->{limit} = $limit if $limit;
1593     $args->{offset} = $offset if $offset;
1594
1595     if (my $max_age = $self->ctx->{get_org_setting}->(
1596         $e->requestor->home_ou, "opac.payment_history_age_limit"
1597     )) {
1598         my $min_ts = DateTime->now(
1599             "time_zone" => DateTime::TimeZone->new("name" => "local"),
1600         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1601         
1602         $logger->info("XXX min_ts: $min_ts");
1603         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1604     }
1605
1606     $self->ctx->{payments} = $U->simplereq(
1607         'open-ils.actor',
1608         'open-ils.actor.user.payments.retrieve.atomic',
1609         $e->authtoken, $e->requestor->id, $args);
1610
1611     return Apache2::Const::OK;
1612 }
1613
1614 # 1. caches the form parameters
1615 # 2. loads the credit card payment "Processing..." page
1616 sub load_myopac_pay_init {
1617     my $self = shift;
1618     my $cache = OpenSRF::Utils::Cache->new('global');
1619
1620     my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1621
1622     if (!@payment_xacts) {
1623         # for consistency with load_myopac_payment_form() and
1624         # to preserve backwards compatibility, if no xacts are
1625         # selected, assume all (applicable) transactions are wanted.
1626         my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1627         return $stat if $stat;
1628         @payment_xacts =
1629             map { $_->{xact}->id } (
1630                 @{$self->ctx->{fines}->{circulation}}, 
1631                 @{$self->ctx->{fines}->{grocery}}
1632         );
1633     }
1634
1635     return $self->generic_redirect unless @payment_xacts;
1636
1637     my $cc_args = {"where_process" => 1};
1638
1639     $cc_args->{$_} = $self->cgi->param($_) for (qw/
1640         number cvv2 expire_year expire_month billing_first
1641         billing_last billing_address billing_city billing_state
1642         billing_zip stripe_token
1643     /);
1644
1645     my $cache_args = {
1646         cc_args => $cc_args, 
1647         user => $self->ctx->{user}->id,
1648         xacts => \@payment_xacts
1649     };
1650
1651     # generate a temporary cache token and cache the form data
1652     my $token = md5_hex($$ . time() . rand());
1653     $cache->put_cache($token, $cache_args, 30);
1654
1655     $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1656
1657     # after we render the processing page, we quickly redirect to submit
1658     # the actual payment.  The refresh url contains the payment token.
1659     # It also contains the list of xact IDs, which allows us to clear the 
1660     # cache at the earliest possible time while leaving a trace of which 
1661     # transactions we were processing, so the UI can bring the user back
1662     # to the payment form w/ the same xacts if the payment fails.
1663
1664     my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1665     $refresh .= ";xact=$_" for @payment_xacts;
1666     $self->ctx->{refresh} = $refresh;
1667
1668     return Apache2::Const::OK;
1669 }
1670
1671 # retrieve the cached CC payment info and send off for processing
1672 sub load_myopac_pay {
1673     my $self = shift;
1674     my $token = $self->ctx->{page_args}->[0];
1675     return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1676
1677     my $cache = OpenSRF::Utils::Cache->new('global');
1678     my $cache_args = $cache->get_cache($token);
1679     $cache->delete_cache($token);
1680
1681     # this page is loaded immediately after the token is created.
1682     # if the cached data is not there, it's because of an invalid
1683     # token (or cache failure) and not because of a timeout.
1684     return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1685
1686     my @payment_xacts = @{$cache_args->{xacts}};
1687     my $cc_args = $cache_args->{cc_args};
1688
1689     # as an added security check, verify the user submitting 
1690     # the form is the same as the user whose data was cached
1691     return Apache2::Const::HTTP_BAD_REQUEST unless
1692         $cache_args->{user} == $self->ctx->{user}->id;
1693
1694     $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1695
1696     my $r;
1697     $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1698
1699     # balance_owed is computed specifically from the fines we're paying
1700     if ($self->ctx->{fines}->{balance_owed} <= 0) {
1701         $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1702         return Apache2::Const::HTTP_BAD_REQUEST;
1703     }
1704
1705     my $args = {
1706         "cc_args" => $cc_args,
1707         "userid" => $self->ctx->{user}->id,
1708         "payment_type" => "credit_card_payment",
1709         "payments" => $self->prepare_fines_for_payment  # should be safe after self->prepare_fines
1710     };
1711
1712     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1713         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1714     );
1715
1716     $self->ctx->{"payment_response"} = $resp;
1717
1718     unless ($resp->{"textcode"}) {
1719         $self->ctx->{printable_receipt} = $U->simplereq(
1720            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1721            $self->editor->authtoken, $resp->{payments}
1722         );
1723     }
1724
1725     return Apache2::Const::OK;
1726 }
1727
1728 sub load_myopac_receipt_print {
1729     my $self = shift;
1730
1731     $self->ctx->{printable_receipt} = $U->simplereq(
1732        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1733        $self->editor->authtoken, [$self->cgi->param("payment")]
1734     );
1735
1736     return Apache2::Const::OK;
1737 }
1738
1739 sub load_myopac_receipt_email {
1740     my $self = shift;
1741
1742     # The following ML method doesn't actually check whether the user in
1743     # question has an email address, so we do.
1744     if ($self->ctx->{user}->email) {
1745         $self->ctx->{email_receipt_result} = $U->simplereq(
1746            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1747            $self->editor->authtoken, [$self->cgi->param("payment")]
1748         );
1749     } else {
1750         $self->ctx->{email_receipt_result} =
1751             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1752     }
1753
1754     return Apache2::Const::OK;
1755 }
1756
1757 sub prepare_fines {
1758     my ($self, $limit, $offset, $id_list) = @_;
1759
1760     # XXX TODO: check for failure after various network calls
1761
1762     # It may be unclear, but this result structure lumps circulation and
1763     # reservation fines together, and keeps grocery fines separate.
1764     $self->ctx->{"fines"} = {
1765         "circulation" => [],
1766         "grocery" => [],
1767         "total_paid" => 0,
1768         "total_owed" => 0,
1769         "balance_owed" => 0
1770     };
1771
1772     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1773
1774     # TODO: This should really be a ML call, but the existing calls 
1775     # return an excessive amount of data and don't offer streaming
1776
1777     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1778
1779     my $req = $cstore->request(
1780         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1781         {
1782             usr => $self->editor->requestor->id,
1783             balance_owed => {'!=' => 0},
1784             ($id_list && @$id_list ? ("id" => $id_list) : ()),
1785         },
1786         {
1787             flesh => 4,
1788             flesh_fields => {
1789                 mobts => [qw/grocery circulation reservation/],
1790                 bresv => ['target_resource_type'],
1791                 brt => ['record'],
1792                 mg => ['billings'],
1793                 mb => ['btype'],
1794                 circ => ['target_copy'],
1795                 acp => ['call_number'],
1796                 acn => ['record']
1797             },
1798             order_by => { mobts => 'xact_start' },
1799             %paging
1800         }
1801     );
1802
1803     my @total_keys = qw/total_paid total_owed balance_owed/;
1804     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1805
1806     while(my $resp = $req->recv) {
1807         my $mobts = $resp->content;
1808         my $circ = $mobts->circulation;
1809
1810         my $last_billing;
1811         if($mobts->grocery) {
1812             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1813             $last_billing = pop(@billings);
1814         }
1815
1816         # XXX TODO confirm that the following, and the later division by 100.0
1817         # to get a floating point representation once again, is sufficiently
1818         # "money-safe" math.
1819         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1820
1821         my $marc_xml = undef;
1822         if ($mobts->xact_type eq 'reservation' and
1823             $mobts->reservation->target_resource_type->record) {
1824             $marc_xml = XML::LibXML->new->parse_string(
1825                 $mobts->reservation->target_resource_type->record->marc
1826             );
1827         } elsif ($mobts->xact_type eq 'circulation' and
1828             $circ->target_copy->call_number->id != -1) {
1829             $marc_xml = XML::LibXML->new->parse_string(
1830                 $circ->target_copy->call_number->record->marc
1831             );
1832         }
1833
1834         push(
1835             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1836             {
1837                 xact => $mobts,
1838                 last_grocery_billing => $last_billing,
1839                 marc_xml => $marc_xml
1840             } 
1841         );
1842     }
1843
1844     $cstore->kill_me;
1845
1846     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1847     return;
1848 }
1849
1850 sub prepare_fines_for_payment {
1851     # This assumes $self->prepare_fines has already been run
1852     my ($self) = @_;
1853
1854     my @results = ();
1855     if ($self->ctx->{fines}) {
1856         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1857             @{$self->ctx->{fines}->{circulation}},
1858             @{$self->ctx->{fines}->{grocery}}
1859         );
1860     }
1861
1862     return \@results;
1863 }
1864
1865 sub load_myopac_main {
1866     my $self = shift;
1867     my $limit = $self->cgi->param('limit') || 0;
1868     my $offset = $self->cgi->param('offset') || 0;
1869     $self->ctx->{search_ou} = $self->_get_search_lib();
1870     $self->ctx->{user}->notes(
1871         $self->editor->search_actor_usr_note({
1872             usr => $self->ctx->{user}->id,
1873             pub => 't'
1874         })
1875     );
1876     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1877 }
1878
1879 sub load_myopac_update_email {
1880     my $self = shift;
1881     my $e = $self->editor;
1882     my $ctx = $self->ctx;
1883     my $email = $self->cgi->param('email') || '';
1884     my $current_pw = $self->cgi->param('current_pw') || '';
1885
1886     # needed for most up-to-date email address
1887     if (my $r = $self->prepare_extended_user_info) { return $r };
1888
1889     return Apache2::Const::OK 
1890         unless $self->cgi->request_method eq 'POST';
1891
1892     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1893         $ctx->{invalid_email} = $email;
1894         return Apache2::Const::OK;
1895     }
1896
1897     my $stat = $U->simplereq(
1898         'open-ils.actor', 
1899         'open-ils.actor.user.email.update', 
1900         $e->authtoken, $email, $current_pw);
1901
1902     if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1903         $ctx->{password_incorrect} = 1;
1904         return Apache2::Const::OK;
1905     }
1906
1907     unless ($self->cgi->param("redirect_to")) {
1908         my $url = $self->apache->unparsed_uri;
1909         $url =~ s/update_email/prefs/;
1910
1911         return $self->generic_redirect($url);
1912     }
1913
1914     return $self->generic_redirect;
1915 }
1916
1917 sub load_myopac_update_username {
1918     my $self = shift;
1919     my $e = $self->editor;
1920     my $ctx = $self->ctx;
1921     my $username = $self->cgi->param('username') || '';
1922     my $current_pw = $self->cgi->param('current_pw') || '';
1923
1924     $self->prepare_extended_user_info;
1925
1926     my $allow_change = 1;
1927     my $regex_check;
1928     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1929     if(defined($lock_usernames) and $lock_usernames == 1) {
1930         # Policy says no username changes
1931         $allow_change = 0;
1932     } else {
1933         # We want this further down.
1934         $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1935         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1936         if(!$username_unlimit) {
1937             if(!$regex_check) {
1938                 # Default is "starts with a number"
1939                 $regex_check = '^\d+';
1940             }
1941             # You already have a username?
1942             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1943                 $allow_change = 0;
1944             }
1945         }
1946     }
1947     if(!$allow_change) {
1948         my $url = $self->apache->unparsed_uri;
1949         $url =~ s/update_username/prefs/;
1950
1951         return $self->generic_redirect($url);
1952     }
1953
1954     return Apache2::Const::OK 
1955         unless $self->cgi->request_method eq 'POST';
1956
1957     unless($username and $username !~ /\s/) { # any other username restrictions?
1958         $ctx->{invalid_username} = $username;
1959         return Apache2::Const::OK;
1960     }
1961
1962     # New username can't look like a barcode if we have a barcode regex
1963     if($regex_check and $username =~ /$regex_check/) {
1964         $ctx->{invalid_username} = $username;
1965         return Apache2::Const::OK;
1966     }
1967
1968     # New username has to look like a username if we have a username regex
1969     $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1970     if($regex_check and $username !~ /$regex_check/) {
1971         $ctx->{invalid_username} = $username;
1972         return Apache2::Const::OK;
1973     }
1974
1975     if($username ne $e->requestor->usrname) {
1976
1977         my $evt = $U->simplereq(
1978             'open-ils.actor', 
1979             'open-ils.actor.user.username.update', 
1980             $e->authtoken, $username, $current_pw);
1981
1982         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1983             $ctx->{password_incorrect} = 1;
1984             return Apache2::Const::OK;
1985         }
1986
1987         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1988             $ctx->{username_exists} = $username;
1989             return Apache2::Const::OK;
1990         }
1991     }
1992
1993     my $url = $self->apache->unparsed_uri;
1994     $url =~ s/update_username/prefs/;
1995
1996     return $self->generic_redirect($url);
1997 }
1998
1999 sub load_myopac_update_password {
2000     my $self = shift;
2001     my $e = $self->editor;
2002     my $ctx = $self->ctx;
2003
2004     return Apache2::Const::OK 
2005         unless $self->cgi->request_method eq 'POST';
2006
2007     my $current_pw = $self->cgi->param('current_pw') || '';
2008     my $new_pw = $self->cgi->param('new_pw') || '';
2009     my $new_pw2 = $self->cgi->param('new_pw2') || '';
2010
2011     unless($new_pw eq $new_pw2) {
2012         $ctx->{password_nomatch} = 1;
2013         return Apache2::Const::OK;
2014     }
2015
2016     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2017
2018     if(!$pw_regex) {
2019         # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2020         $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2021     }
2022
2023     if($pw_regex and $new_pw !~ /$pw_regex/) {
2024         $ctx->{password_invalid} = 1;
2025         return Apache2::Const::OK;
2026     }
2027
2028     my $evt = $U->simplereq(
2029         'open-ils.actor', 
2030         'open-ils.actor.user.password.update', 
2031         $e->authtoken, $new_pw, $current_pw);
2032
2033
2034     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2035         $ctx->{password_incorrect} = 1;
2036         return Apache2::Const::OK;
2037     }
2038
2039     my $url = $self->apache->unparsed_uri;
2040     $url =~ s/update_password/prefs/;
2041
2042     return $self->generic_redirect($url);
2043 }
2044
2045 sub _update_bookbag_metadata {
2046     my ($self, $bookbag) = @_;
2047
2048     $bookbag->name($self->cgi->param("name"));
2049     $bookbag->description($self->cgi->param("description"));
2050
2051     return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2052     return 0;
2053 }
2054
2055 sub _get_lists_per_page {
2056     my $self = shift;
2057
2058     if($self->editor->requestor) {
2059         $self->timelog("Checking for opac.lists_per_page preference");
2060         # See if the user has a lists per page preference
2061         my $ipp = $self->editor->search_actor_user_setting({
2062             usr => $self->editor->requestor->id,
2063             name => 'opac.lists_per_page'
2064         })->[0];
2065         $self->timelog("Got opac.lists_per_page preference");
2066         return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2067     }
2068     return 10; # default
2069 }
2070
2071 sub _get_items_per_page {
2072     my $self = shift;
2073
2074     if($self->editor->requestor) {
2075         $self->timelog("Checking for opac.list_items_per_page preference");
2076         # See if the user has a list items per page preference
2077         my $ipp = $self->editor->search_actor_user_setting({
2078             usr => $self->editor->requestor->id,
2079             name => 'opac.list_items_per_page'
2080         })->[0];
2081         $self->timelog("Got opac.list_items_per_page preference");
2082         return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2083     }
2084     return 10; # default
2085 }
2086
2087 sub load_myopac_bookbags {
2088     my $self = shift;
2089     my $e = $self->editor;
2090     my $ctx = $self->ctx;
2091     my $limit = $self->_get_lists_per_page || 10;
2092     my $offset = $self->cgi->param('offset') || 0;
2093
2094     $ctx->{bookbags_limit} = $limit;
2095     $ctx->{bookbags_offset} = $offset;
2096
2097     # for list item pagination
2098     my $item_limit = $self->_get_items_per_page;
2099     my $item_page = $self->cgi->param('item_page') || 1;
2100     my $item_offset = ($item_page - 1) * $item_limit;
2101     $ctx->{bookbags_item_page} = $item_page;
2102
2103     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2104     $e->xact_begin; # replication...
2105
2106     my $rv = $self->load_mylist;
2107     unless($rv eq Apache2::Const::OK) {
2108         $e->rollback;
2109         return $rv;
2110     }
2111
2112     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2113         [
2114             {owner => $e->requestor->id, btype => 'bookbag'}, {
2115                 order_by => {cbreb => 'name'},
2116                 limit => $limit,
2117                 offset => $offset
2118             }
2119         ],
2120         {substream => 1}
2121     );
2122
2123     if(!$ctx->{bookbags}) {
2124         $e->rollback;
2125         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2126     }
2127
2128     # We load the user prefs to get their default bookbag.
2129     $self->_load_user_with_prefs;
2130
2131     # We also want a total count of the user's bookbags.
2132     my $q = {
2133         'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2134         'from' => 'cbreb',
2135         'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2136     };
2137     my $r = $e->json_query($q);
2138     $ctx->{bookbag_count} = $r->[0]->{'count'};
2139
2140     # If the user wants a specific bookbag's items, load them.
2141
2142     if ($self->cgi->param("bbid")) {
2143         my ($bookbag) =
2144             grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2145
2146         if ($bookbag) {
2147             my $query = $self->_prepare_bookbag_container_query(
2148                 $bookbag->id, $sorter, $modifier
2149             );
2150
2151             # Calculate total count of the items in selected bookbag.
2152             # This total includes record entries that have no assets available.
2153             my $bb_search_results = $U->simplereq(
2154                 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2155                 {"limit" => 1, "offset" => 0}, $query
2156             ); # we only need the count, so do the actual search with limit=1
2157
2158             if ($bb_search_results) {
2159                 $ctx->{bb_item_count} = $bb_search_results->{count};
2160             } else {
2161                 $logger->warn("search failed in load_myopac_bookbags()");
2162                 $ctx->{bb_item_count} = 0; # fallback value
2163             }
2164
2165             #calculate page count
2166             $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2167
2168             if ( ($self->cgi->param("action") || '') eq "editmeta") {
2169                 if (!$self->_update_bookbag_metadata($bookbag))  {
2170                     $e->rollback;
2171                     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2172                 } else {
2173                     $e->commit;
2174                     my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2175                         $bookbag->id;
2176
2177                     foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2178                         if ($self->cgi->param($param)) {
2179                             $url .= ";$param=" . uri_escape_utf8($self->cgi->param($param));
2180                         }
2181                     }
2182
2183                     return $self->generic_redirect($url);
2184                 }
2185             }
2186
2187             # we're done with our CStoreEditor.  Rollback here so 
2188             # later calls don't cause a timeout, resulting in a 
2189             # transaction rollback under the covers.
2190             $e->rollback;
2191
2192
2193             # For list items pagination
2194             my $args = {
2195                 "limit" => $item_limit,
2196                 "offset" => $item_offset
2197             };
2198
2199             my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2200                 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2201
2202             # capture pref_ou for callnumber filter/display
2203             $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2204
2205             # search for local callnumbers for display
2206             my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2207
2208             my (undef, @recs) = $self->get_records_and_facets(
2209                 [ map {$_->target_biblio_record_entry->id} @$items ],
2210                 undef, 
2211                 {
2212                     flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2213                     flesh_depth => 1,
2214                     site => $ctx->{get_aou}->($focus_ou)->shortname,
2215                     pref_lib => $ctx->{pref_ou}
2216                 }
2217             );
2218
2219             $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2220
2221             $bookbag->items($items);
2222         }
2223     }
2224
2225     # If we have add_rec, we got here from the "Add to new list"
2226     # or "See all" popmenu items.
2227     if (my $add_rec = $self->cgi->param('add_rec')) {
2228         $self->ctx->{add_rec} = $add_rec;
2229         # But not in the staff client, 'cause that breaks things.
2230         unless ($self->ctx->{is_staff}) {
2231             # allow caller to provide the where_from in cases where
2232             # the referer is an intermediate error page
2233             if ($self->cgi->param('where_from')) {
2234                 $self->ctx->{where_from} = $self->cgi->param('where_from');
2235             } else {
2236                 $self->ctx->{where_from} = $self->ctx->{referer};
2237                 if ( my $anchor = $self->cgi->param('anchor') ) {
2238                     $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
2239                 }
2240             }
2241         }
2242     }
2243
2244     # this rollback may be a dupe, but that's OK because 
2245     # cstoreditor ignores dupe rollbacks
2246     $e->rollback;
2247
2248     return Apache2::Const::OK;
2249 }
2250
2251
2252 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
2253 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
2254 sub load_myopac_bookbag_update {
2255     my ($self, $action, $list_id, @hold_recs) = @_;
2256     my $e = $self->editor;
2257     my $cgi = $self->cgi;
2258
2259     # save_notes is effectively another action, but is passed in a separate
2260     # CGI parameter for what are really just layout reasons.
2261     $action = 'save_notes' if $cgi->param('save_notes');
2262     $action ||= $cgi->param('action');
2263
2264     $list_id ||= $cgi->param('list') || $cgi->param('bbid');
2265
2266     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
2267     my @selected_item = $cgi->param('selected_item');
2268     my $shared = $cgi->param('shared');
2269     my $name = $cgi->param('name');
2270     my $description = $cgi->param('description');
2271     my $success = 0;
2272     my $list;
2273
2274     # This url intentionally leaves off the edit_notes parameter, but
2275     # may need to add some back in for paging.
2276
2277     my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
2278         $self->ctx->{opac_root} . "/myopac/lists?";
2279
2280     foreach my $param (('loc', 'qtype', 'query', 'sort')) {
2281         if ($cgi->param($param)) {
2282             $url .= "$param=" . uri_escape_utf8($cgi->param($param)) . ";";
2283         }
2284     }
2285
2286     if ($action eq 'create') {
2287
2288         if ($name) {
2289             $list = Fieldmapper::container::biblio_record_entry_bucket->new;
2290             $list->name($name);
2291             $list->description($description);
2292             $list->owner($e->requestor->id);
2293             $list->btype('bookbag');
2294             $list->pub($shared ? 't' : 'f');
2295             $success = $U->simplereq('open-ils.actor',
2296                 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
2297             if (ref($success) ne 'HASH' && scalar @add_rec) {
2298                 $list_id = (ref($success)) ? $success->id : $success;
2299                 foreach my $add_rec (@add_rec) {
2300                     my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2301                     $item->bucket($list_id);
2302                     $item->target_biblio_record_entry($add_rec);
2303                     $success = $U->simplereq('open-ils.actor',
2304                                              'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2305                     last unless $success;
2306                 }
2307             }
2308             $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
2309
2310         } else { # no name
2311             $self->ctx->{bucket_failure_noname} = 1;
2312         }
2313
2314     } elsif($action eq 'place_hold') {
2315
2316         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
2317         unless (@hold_recs) {
2318             if (@selected_item) {
2319                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
2320                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
2321             }
2322         }
2323                 
2324         return Apache2::Const::OK unless @hold_recs;
2325         $logger->info("placing holds from list page on: @hold_recs");
2326
2327         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
2328         $url .= ';hold_target=' . $_ for @hold_recs;
2329         foreach my $param (('loc', 'qtype', 'query')) {
2330             if ($cgi->param($param)) {
2331                 $url .= ";$param=" . uri_escape_utf8($cgi->param($param));
2332             }
2333         }
2334         return $self->generic_redirect($url);
2335
2336     } else {
2337
2338         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
2339
2340         return Apache2::Const::HTTP_BAD_REQUEST unless 
2341             $list and $list->owner == $e->requestor->id;
2342     }
2343
2344     if($action eq 'delete') {
2345         $success = $U->simplereq('open-ils.actor', 
2346             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
2347         if ($success) {
2348             # We check to see if we're deleting the user's default list.
2349             $self->_load_user_with_prefs;
2350             my $settings_map = $self->ctx->{user_setting_map};
2351             if ($$settings_map{'opac.default_list'} == $list_id) {
2352                 # We unset the user's opac.default_list setting.
2353                 $success = $U->simplereq(
2354                     'open-ils.actor',
2355                     'open-ils.actor.patron.settings.update',
2356                     $e->authtoken,
2357                     $e->requestor->id,
2358                     { 'opac.default_list' => 0 }
2359                 );
2360             }
2361         }
2362     } elsif($action eq 'show') {
2363         unless($U->is_true($list->pub)) {
2364             $list->pub('t');
2365             $success = $U->simplereq('open-ils.actor', 
2366                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2367         }
2368
2369     } elsif($action eq 'hide') {
2370         if($U->is_true($list->pub)) {
2371             $list->pub('f');
2372             $success = $U->simplereq('open-ils.actor', 
2373                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2374         }
2375
2376     } elsif($action eq 'rename') {
2377         if($name) {
2378             $list->name($name);
2379             $success = $U->simplereq('open-ils.actor', 
2380                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
2381         }
2382
2383     } elsif($action eq 'add_rec') {
2384         foreach my $add_rec (@add_rec) {
2385             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2386             $item->bucket($list_id);
2387             $item->target_biblio_record_entry($add_rec);
2388             $success = $U->simplereq('open-ils.actor', 
2389                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
2390             last unless $success;
2391         }
2392         # Redirect back where we came from if we have an anchor parameter:
2393         if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
2394             $url = $self->ctx->{referer};
2395             $url =~ s/#.*|$/#$anchor/;
2396         } elsif ($cgi->param('where_from')) {
2397             # Or, if we have a "where_from" parameter.
2398             $url = $cgi->param('where_from');
2399         }
2400     } elsif ($action eq 'del_item') {
2401         foreach (@selected_item) {
2402             $success = $U->simplereq(
2403                 'open-ils.actor',
2404                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
2405             );
2406             last unless $success;
2407         }
2408     } elsif ($action eq 'save_notes') {
2409         $success = $self->update_bookbag_item_notes;
2410         $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
2411     } elsif ($action eq 'make_default') {
2412         $success = $U->simplereq(
2413             'open-ils.actor',
2414             'open-ils.actor.patron.settings.update',
2415             $e->authtoken,
2416             $list->owner,
2417             { 'opac.default_list' => $list_id }
2418         );
2419     } elsif ($action eq 'remove_default') {
2420         $success = $U->simplereq(
2421             'open-ils.actor',
2422             'open-ils.actor.patron.settings.update',
2423             $e->authtoken,
2424             $list->owner,
2425             { 'opac.default_list' => 0 }
2426         );
2427     }
2428
2429     return $self->generic_redirect($url) if $success;
2430
2431     $self->ctx->{where_from} = $cgi->param('where_from');
2432     $self->ctx->{bucket_action} = $action;
2433     $self->ctx->{bucket_action_failed} = 1;
2434     return Apache2::Const::OK;
2435 }
2436
2437 sub update_bookbag_item_notes {
2438     my ($self) = @_;
2439     my $e = $self->editor;
2440
2441     my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2442     my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2443
2444     # We're going to leverage an API call that's already been written to check
2445     # permissions appropriately.
2446
2447     my $a = create OpenSRF::AppSession("open-ils.actor");
2448     my $method = "open-ils.actor.container.item_note.cud";
2449
2450     for my $note_key (@note_keys) {
2451         my $note;
2452
2453         my $id = ($note_key =~ /(\d+)/)[0];
2454
2455         if (!($note =
2456             $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2457             my $event = $e->die_event;
2458             $self->apache->log->warn(
2459                 "error retrieving cbrebin id $id, got event " .
2460                 $event->{textcode}
2461             );
2462             $a->kill_me;
2463             $self->ctx->{bucket_action_event} = $event;
2464             return;
2465         }
2466
2467         if (length($self->cgi->param($note_key))) {
2468             $note->ischanged(1);
2469             $note->note($self->cgi->param($note_key));
2470         } else {
2471             $note->isdeleted(1);
2472         }
2473
2474         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2475
2476         if (defined $U->event_code($r)) {
2477             $self->apache->log->warn(
2478                 "attempt to modify cbrebin " . $note->id .
2479                 " returned event " .  $r->{textcode}
2480             );
2481             $e->rollback;
2482             $a->kill_me;
2483             $self->ctx->{bucket_action_event} = $r;
2484             return;
2485         }
2486     }
2487
2488     for my $item_key (@item_keys) {
2489         my $id = int(($item_key =~ /(\d+)/)[0]);
2490         my $text = $self->cgi->param($item_key);
2491
2492         chomp $text;
2493         next unless length $text;
2494
2495         my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2496         $note->isnew(1);
2497         $note->item($id);
2498         $note->note($text);
2499
2500         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2501
2502         if (defined $U->event_code($r)) {
2503             $self->apache->log->warn(
2504                 "attempt to create cbrebin for item " . $note->item .
2505                 " returned event " .  $r->{textcode}
2506             );
2507             $e->rollback;
2508             $a->kill_me;
2509             $self->ctx->{bucket_action_event} = $r;
2510             return;
2511         }
2512     }
2513
2514     $a->kill_me;
2515     return 1;   # success
2516 }
2517
2518 sub load_myopac_bookbag_print {
2519     my ($self) = @_;
2520
2521     my $id = int($self->cgi->param("list"));
2522
2523     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2524
2525     my $item_search =
2526         $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2527
2528     my $bbag;
2529
2530     # Get the bookbag object itself, assuming we're allowed to.
2531     if ($self->editor->allowed("VIEW_CONTAINER")) {
2532
2533         $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2534     } else {
2535         my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2536             {
2537                 "id" => $id,
2538                 "-or" => {
2539                     "owner" => $self->editor->requestor->id,
2540                     "pub" => "t"
2541                 }
2542             }
2543         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2544
2545         $bbag = pop @$bookbags;
2546     }
2547
2548     # If we have a bookbag we're allowed to look at, issue the A/T event
2549     # to get CSV, passing as a user param that search query we built before.
2550     if ($bbag) {
2551         $self->ctx->{csv} = $U->fire_object_event(
2552             undef, "container.biblio_record_entry_bucket.csv",
2553             $bbag, $self->editor->requestor->home_ou,
2554             undef, {"item_search" => $item_search}
2555         );
2556     }
2557
2558     # Create a reasonable filename and set the content disposition to
2559     # provoke browser download dialogs.
2560     (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2561
2562     return $self->set_file_download_headers("$filename.csv");
2563 }
2564
2565 sub load_myopac_circ_history_export {
2566     my $self = shift;
2567     my $e = $self->editor;
2568     my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2569
2570     my $ids = $e->json_query({
2571         select => {
2572             au => [{
2573                 column => 'id', 
2574                 transform => 'action.usr_visible_circs', 
2575                 result_field => 'id'
2576             }]
2577         },
2578         from => 'au',
2579         where => {id => $e->requestor->id} 
2580     });
2581
2582     $self->ctx->{csv} = $U->fire_object_event(
2583         undef, 
2584         'circ.format.history.csv',
2585         $e->search_action_circulation({id => [map {$_->{id}} @$ids]}, {substream =>1}),
2586         $self->editor->requestor->home_ou
2587     );
2588
2589     return $self->set_file_download_headers($filename);
2590 }
2591
2592 sub load_password_reset {
2593     my $self = shift;
2594     my $cgi = $self->cgi;
2595     my $ctx = $self->ctx;
2596     my $barcode = $cgi->param('barcode');
2597     my $username = $cgi->param('username');
2598     my $email = $cgi->param('email');
2599     my $pwd1 = $cgi->param('pwd1');
2600     my $pwd2 = $cgi->param('pwd2');
2601     my $uuid = $ctx->{page_args}->[0];
2602
2603     if ($uuid) {
2604
2605         $logger->info("patron password reset with uuid $uuid");
2606
2607         if ($pwd1 and $pwd2) {
2608
2609             if ($pwd1 eq $pwd2) {
2610
2611                 my $response = $U->simplereq(
2612                     'open-ils.actor', 
2613                     'open-ils.actor.patron.password_reset.commit',
2614                     $uuid, $pwd1);
2615
2616                 $logger->info("patron password reset response " . Dumper($response));
2617
2618                 if ($U->event_code($response)) { # non-success event
2619                     
2620                     my $code = $response->{textcode};
2621                     
2622                     if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2623                         $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2624                     }
2625
2626                     if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2627                         $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2628                     }
2629
2630                 } else { # success
2631
2632                     $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2633                 }
2634
2635             } else { # passwords not equal
2636
2637                 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2638             }
2639
2640         } else { # 2 password values needed
2641
2642             $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2643         }
2644
2645     } elsif ($barcode or $username) {
2646
2647         my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2648         push(@params, $email) if $email;
2649
2650         $U->simplereq(
2651             'open-ils.actor', 
2652             'open-ils.actor.patron.password_reset.request', @params);
2653
2654         $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2655     }
2656
2657     $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2658     return Apache2::Const::OK;
2659 }
2660
2661 1;