]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
Allow overriding some hold events when permissions apply
[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 DateTime;
11 my $U = 'OpenILS::Application::AppUtils';
12
13 sub prepare_extended_user_info {
14     my $self = shift;
15     my @extra_flesh = @_;
16
17     $self->ctx->{user} = $self->editor->retrieve_actor_user([
18         $self->ctx->{user}->id,
19         {
20             flesh => 1,
21             flesh_fields => {
22                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
23                 # ...
24             }
25         }
26     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
27
28     return;
29 }
30
31 # Given an event returned by a failed attempt to create a hold, do we have
32 # permission to override?  XXX Should the permission check be scoped to a
33 # given org_unit context?
34 sub test_could_override {
35     my ($self) = @_;
36     my $event = $self->ctx->{"hold_failed_event"};
37
38     return 0 unless $event;
39     return 1 if $self->editor->allowed($event . ".override");
40     return 1 if $event->{"fail_part"} and
41         $self->editor->allowed($event->{"fail_part"} . ".override");
42     return 0;
43 }
44
45 # Find out whether we care that local copies are available
46 sub local_avail_concern {
47     my ($self, $allowed, $request_lib) = @_;
48
49     my ($block, $alert);
50     if ($allowed->{"success"} and $allowed->{"local_avail"}) {
51         $block = $self->ctx->{get_org_setting}->
52             ($request_lib, "circ.holds.hold_has_copy_at.block");
53         $alert = (
54             $self->ctx->{get_org_setting}->
55                 ($request_lib, "circ.holds.hold_has_copy_at.alert")
56                 and not $self->cgi->param("override")
57         );
58     }
59     return ($block, $alert);
60 }
61
62 # context additions: 
63 #   user : au object, fleshed
64 sub load_myopac_prefs {
65     my $self = shift;
66     return $self->prepare_extended_user_info || Apache2::Const::OK;
67 }
68
69 sub load_myopac_prefs_notify {
70     my $self = shift;
71     my $e = $self->editor;
72
73     my $user_prefs = $self->fetch_optin_prefs;
74     $user_prefs = $self->update_optin_prefs($user_prefs)
75         if $self->cgi->request_method eq 'POST';
76
77     $self->ctx->{opt_in_settings} = $user_prefs; 
78
79     return Apache2::Const::OK;
80 }
81
82 sub fetch_optin_prefs {
83     my $self = shift;
84     my $e = $self->editor;
85
86     # fetch all of the opt-in settings the user has access to
87     # XXX: user's should in theory have options to opt-in to notices
88     # for remote locations, but that opens the door for a large
89     # set of generally un-used opt-ins.. needs discussion
90     my $opt_ins =  $U->simplereq(
91         'open-ils.actor',
92         'open-ils.actor.event_def.opt_in.settings.atomic',
93         $e->authtoken, $e->requestor->home_ou);
94
95     # fetch user setting values for each of the opt-in settings
96     my $user_set = $U->simplereq(
97         'open-ils.actor',
98         'open-ils.actor.patron.settings.retrieve',
99         $e->authtoken, 
100         $e->requestor->id, 
101         [map {$_->name} @$opt_ins]
102     );
103
104     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
105 }
106
107 sub update_optin_prefs {
108     my $self = shift;
109     my $user_prefs = shift;
110     my $e = $self->editor;
111     my @settings = $self->cgi->param('setting');
112     my %newsets;
113
114     # apply now-true settings
115     for my $applied (@settings) {
116         # see if setting is already applied to this user
117         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
118         $newsets{$applied} = OpenSRF::Utils::JSON->true;
119     }
120
121     # remove now-false settings
122     for my $pref (grep { $_->{value} } @$user_prefs) {
123         $newsets{$pref->{cust}->name} = undef 
124             unless grep { $_ eq $pref->{cust}->name } @settings;
125     }
126
127     $U->simplereq(
128         'open-ils.actor',
129         'open-ils.actor.patron.settings.update',
130         $e->authtoken, $e->requestor->id, \%newsets);
131
132     # update the local prefs to match reality
133     for my $pref (@$user_prefs) {
134         $pref->{value} = $newsets{$pref->{cust}->name} 
135             if exists $newsets{$pref->{cust}->name};
136     }
137
138     return $user_prefs;
139 }
140
141 sub _load_user_with_prefs {
142     my $self = shift;
143     my $stat = $self->prepare_extended_user_info('settings');
144     return $stat if $stat; # not-OK
145
146     $self->ctx->{user_setting_map} = {
147         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
148             @{$self->ctx->{user}->settings}
149     };
150
151     return undef;
152 }
153
154 sub load_myopac_prefs_settings {
155     my $self = shift;
156
157     my $stat = $self->_load_user_with_prefs;
158     return $stat if $stat;
159
160     return Apache2::Const::OK
161         unless $self->cgi->request_method eq 'POST';
162
163     # some setting values from the form don't match the 
164     # required value/format for the db, so they have to be 
165     # individually translated.
166
167     my %settings;
168     my $set_map = $self->ctx->{user_setting_map};
169
170     my $key = 'opac.hits_per_page';
171     my $val = $self->cgi->param($key);
172     $settings{$key}= $val unless $$set_map{$key} eq $val;
173
174     my $now = DateTime->now->strftime('%F');
175     for $key (qw/history.circ.retention_start history.hold.retention_start/) {
176         $val = $self->cgi->param($key);
177         if($val and $val eq 'on') {
178             # Set the start time to 'now' unless a start time already exists for the user
179             $settings{$key} = $now unless $$set_map{$key};
180         } else {
181             # clear the start time if one previously existed for the user
182             $settings{$key} = undef if $$set_map{$key};
183         }
184     }
185     
186     # Send the modified settings off to be saved
187     $U->simplereq(
188         'open-ils.actor', 
189         'open-ils.actor.patron.settings.update',
190         $self->editor->authtoken, undef, \%settings);
191
192     # re-fetch user prefs 
193     $self->ctx->{updated_user_settings} = \%settings;
194     return $self->_load_user_with_prefs || Apache2::Const::OK;
195 }
196
197 sub fetch_user_holds {
198     my $self = shift;
199     my $hold_ids = shift;
200     my $ids_only = shift;
201     my $flesh = shift;
202     my $available = shift;
203     my $limit = shift;
204     my $offset = shift;
205
206     my $e = $self->editor;
207
208     my $circ = OpenSRF::AppSession->create('open-ils.circ');
209
210     if(!$hold_ids) {
211
212         $hold_ids = $circ->request(
213             'open-ils.circ.holds.id_list.retrieve.authoritative', 
214             $e->authtoken, 
215             $e->requestor->id
216         )->gather(1);
217     
218         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
219     }
220
221
222     return $hold_ids if $ids_only or @$hold_ids == 0;
223
224     my $args = {
225         suppress_notices => 1,
226         suppress_transits => 1,
227         suppress_mvr => 1,
228         suppress_patron_details => 1,
229         include_bre => $flesh ? 1 : 0
230     };
231
232     # ----------------------------------------------------------------
233     # Collect holds in batches of $batch_size for faster retrieval
234
235     my $batch_size = 8;
236     my $batch_idx = 0;
237     my $mk_req_batch = sub {
238         my @ses;
239         my $top_idx = $batch_idx + $batch_size;
240         while($batch_idx < $top_idx) {
241             my $hold_id = $hold_ids->[$batch_idx++];
242             last unless $hold_id;
243             my $ses = OpenSRF::AppSession->create('open-ils.circ');
244             my $req = $ses->request(
245                 'open-ils.circ.hold.details.retrieve', 
246                 $e->authtoken, $hold_id, $args);
247             push(@ses, {ses => $ses, req => $req});
248         }
249         return @ses;
250     };
251
252     my $first = 1;
253     my(@collected, @holds, @ses);
254
255     while(1) {
256         @ses = $mk_req_batch->() if $first;
257         last if $first and not @ses;
258
259         if(@collected) {
260             # If desired by the caller, filter any holds that are not available.
261             if ($available) {
262                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
263             }
264             while(my $blob = pop(@collected)) {
265                 $blob->{marc_xml} = XML::LibXML->new->parse_string($blob->{hold}->{bre}->marc) if $flesh;
266                 push(@holds, $blob);
267             }
268         }
269
270         for my $req_data (@ses) {
271             push(@collected, {hold => $req_data->{req}->gather(1)});
272             $req_data->{ses}->kill_me;
273         }
274
275         @ses = $mk_req_batch->();
276         last unless @collected or @ses;
277         $first = 0;
278     }
279
280     # put the holds back into the original server sort order
281     my @sorted;
282     for my $id (@$hold_ids) {
283         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
284     }
285
286     return \@sorted;
287 }
288
289 sub handle_hold_update {
290     my $self = shift;
291     my $action = shift;
292     my $e = $self->editor;
293     my $url;
294
295     my @hold_ids = $self->cgi->param('hold_id'); # for non-_all actions
296     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
297
298     my $circ = OpenSRF::AppSession->create('open-ils.circ');
299
300     if($action =~ /cancel/) {
301
302         for my $hold_id (@hold_ids) {
303             my $resp = $circ->request(
304                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
305         }
306
307     } elsif ($action =~ /activate|suspend/) {
308         
309         my $vlist = [];
310         for my $hold_id (@hold_ids) {
311             my $vals = {id => $hold_id};
312
313             if($action =~ /activate/) {
314                 $vals->{frozen} = 'f';
315                 $vals->{thaw_date} = undef;
316
317             } elsif($action =~ /suspend/) {
318                 $vals->{frozen} = 't';
319                 # $vals->{thaw_date} = TODO;
320             }
321             push(@$vlist, $vals);
322         }
323
324         $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
325     } elsif ($action eq 'edit') {
326
327         my @vals = map {
328             my $val = {"id" => $_};
329             $val->{"frozen"} = $self->cgi->param("frozen");
330             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
331
332             for my $field (qw/expire_time thaw_date/) {
333                 # XXX TODO make this support other date formats, not just
334                 # MM/DD/YYYY.
335                 next unless $self->cgi->param($field) =~
336                     m:^(\d{2})/(\d{2})/(\d{4})$:;
337                 $val->{$field} = "$3-$1-$2";
338             }
339             $val;
340         } @hold_ids;
341
342         $circ->request(
343             'open-ils.circ.hold.update.batch.atomic',
344             $e->authtoken, undef, \@vals
345         )->gather(1);   # LFW XXX test for failure
346         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
347     }
348
349     $circ->kill_me;
350     return defined($url) ? $self->generic_redirect($url) : undef;
351 }
352
353 sub load_myopac_holds {
354     my $self = shift;
355     my $e = $self->editor;
356     my $ctx = $self->ctx;
357     
358
359     my $limit = $self->cgi->param('limit') || 0;
360     my $offset = $self->cgi->param('offset') || 0;
361     my $action = $self->cgi->param('action') || '';
362     my $available = int($self->cgi->param('available') || 0);
363
364     my $hold_handle_result;
365     $hold_handle_result = $self->handle_hold_update($action) if $action;
366
367     $ctx->{holds} = $self->fetch_user_holds(undef, 0, 1, $available, $limit, $offset);
368
369     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
370 }
371
372 sub load_place_hold {
373     my $self = shift;
374     my $ctx = $self->ctx;
375     my $gos = $ctx->{get_org_setting};
376     my $e = $self->editor;
377     my $cgi = $self->cgi;
378     $self->ctx->{page} = 'place_hold';
379
380     $ctx->{hold_target} = $cgi->param('hold_target');
381     $ctx->{hold_type} = $cgi->param('hold_type');
382
383     # Although in the context of staff placing holds for other users, this
384     # does not yield the appropriate pickup lib, that situation is addressed
385     # in the client with javascript when possible.
386     $ctx->{default_pickup_lib} = $e->requestor->home_ou;
387
388     my $request_lib = $e->requestor->ws_ou || $e->requestor->home_ou;
389
390     # XXX check for failure of the retrieve_* methods called below, and
391     # possibly replace all the if,elsif with a dispatch table (meh, elegance)
392
393     my $target_field;
394     if ($ctx->{hold_type} eq 'T') {
395         $target_field = "titleid";
396         $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
397     } elsif ($ctx->{hold_type} eq 'V') {
398         $target_field = "volume_id";
399         my $vol = $e->retrieve_asset_call_number([
400             $ctx->{hold_target}, {
401                 "flesh" => 1,
402                 "flesh_fields" => {"acn" => ["record"]}
403             }
404         ]);
405         $ctx->{record} = $vol->record;
406     } elsif ($ctx->{hold_type} eq 'C') {
407         $target_field = "copy_id";
408         my $copy = $e->retrieve_asset_copy([
409             $ctx->{hold_target}, {
410                 "flesh" => 2,
411                 "flesh_fields" => {
412                     "acn" => ["record"],
413                     "acp" => ["call_number"]
414                 }
415             }
416         ]);
417         $ctx->{record} = $copy->call_number->record;
418     } elsif ($ctx->{hold_type} eq 'I') {
419         $target_field = "issuanceid";
420         my $iss = $e->retrieve_serial_issuance([
421             $ctx->{hold_target}, {
422                 "flesh" => 2,
423                 "flesh_fields" => {
424                     "siss" => ["subscription"], "ssub" => ["record_entry"]
425                 }
426             }
427         ]);
428         $ctx->{record} = $iss->subscription->record_entry;
429     }
430     # ...
431
432     $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
433
434     if (my $pickup_lib = $cgi->param('pickup_lib')) {
435         my $requestor = $e->requestor->id;
436         my $usr; 
437
438         if ((not $ctx->{"is_staff"}) or
439             ($cgi->param("hold_usr_is_requestor"))) {
440             $usr = $requestor;
441         } else {
442             my $actor = create OpenSRF::AppSession("open-ils.actor");
443             $usr = $actor->request(
444                 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
445                 $e->authtoken, $cgi->param("hold_usr")
446             )->gather(1);
447
448             if (defined $U->event_code($usr)) {
449                 $ctx->{hold_failed} = 1;
450                 $ctx->{hold_failed_event} = $usr;
451             }
452             # XXX Does $actor need to be explicity disconnected/destroyed?
453         }
454
455         my $args = {
456             patronid => $usr,
457             $target_field => $ctx->{"hold_target"},
458             pickup_lib => $pickup_lib,
459             hold_type => $ctx->{"hold_type"},
460             depth => 0, # XXX
461         };
462
463         my $allowed = $U->simplereq(
464             'open-ils.circ',
465             'open-ils.circ.title_hold.is_possible',
466             $e->authtoken, $args
467         );
468
469         $logger->info('hold permit result ' . OpenSRF::Utils::JSON->perl2JSON($allowed));
470
471         my ($local_block, $local_alert) =
472             $self->local_avail_concern($allowed, $request_lib);
473
474         if ($local_block) {
475             $ctx->{hold_failed} = 1;
476             $ctx->{hold_local_block} = 1;
477         } elsif ($local_alert) {
478             $ctx->{hold_failed} = 1;
479             $ctx->{hold_local_alert} = 1;
480         } elsif ($allowed->{success}) {
481             my $hold = Fieldmapper::action::hold_request->new;
482
483             $hold->pickup_lib($pickup_lib);
484             $hold->requestor($requestor);
485             $hold->usr($usr);
486             $hold->target($ctx->{hold_target});
487             $hold->hold_type($ctx->{hold_type});
488             # frozen, expired, etc..
489
490             my $method =  "open-ils.circ.holds.create";
491             $method .= ".override" if $cgi->param("override");
492
493             my $stat = $U->simplereq(
494                 "open-ils.circ", $method, $e->authtoken, $hold
495             );
496
497             # The following did not cover all the possible return values of
498             # open-ils.circ.holds.create
499             #if($stat and $stat > 0) {
500             if ($stat and (not ref $stat) and $stat > 0) {
501                 # if successful, return the user to the requesting page
502                 $self->apache->log->info(
503                     "Redirecting back to " . $cgi->param('redirect_to')
504                 );
505                 return $self->generic_redirect;
506
507             } else {
508                 $ctx->{hold_failed} = 1;
509
510                 # Give the original CGI params back to the user in case they
511                 # want to try to override something.
512                 $ctx->{orig_params} = $cgi->Vars;
513                 delete $ctx->{orig_params}{submit};
514
515                 if (ref $stat eq 'ARRAY') {
516                     $ctx->{hold_failed_event} = shift @$stat;
517                 } elsif (defined $U->event_code($stat)) {
518                     $ctx->{hold_failed_event} = $stat;
519                 } else {
520                     $self->apache->log->info(
521                         "attempt to create hold returned $stat"
522                     );
523                 }
524
525                 $ctx->{could_override} = $self->test_could_override;
526             }
527         } else { # hold *check* failed
528             $ctx->{hold_failed} = 1; # XXX process the events, etc
529             $ctx->{hold_failed_event} = $allowed->{last_event};
530         }
531
532         # hold permit failed
533     }
534
535     return Apache2::Const::OK;
536 }
537
538
539 sub fetch_user_circs {
540     my $self = shift;
541     my $flesh = shift; # flesh bib data, etc.
542     my $circ_ids = shift;
543     my $limit = shift;
544     my $offset = shift;
545
546     my $e = $self->editor;
547
548     my @circ_ids;
549
550     if($circ_ids) {
551         @circ_ids = @$circ_ids;
552
553     } else {
554
555         my $circ_data = $U->simplereq(
556             'open-ils.actor', 
557             'open-ils.actor.user.checked_out',
558             $e->authtoken, 
559             $e->requestor->id
560         );
561
562         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
563
564         if($limit or $offset) {
565             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
566         }
567     }
568
569     return [] unless @circ_ids;
570
571     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
572
573     my $qflesh = {
574         flesh => 3,
575         flesh_fields => {
576             circ => ['target_copy'],
577             acp => ['call_number'],
578             acn => ['record']
579         }
580     };
581
582     $e->xact_begin;
583     my $circs = $e->search_action_circulation(
584         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
585
586     my @circs;
587     for my $circ (@$circs) {
588         push(@circs, {
589             circ => $circ, 
590             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
591                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
592                 undef  # pre-cat copy, use the dummy title/author instead
593         });
594     }
595     $e->xact_rollback;
596
597     # make sure the final list is in the correct order
598     my @sorted_circs;
599     for my $id (@circ_ids) {
600         push(
601             @sorted_circs,
602             (grep { $_->{circ}->id == $id } @circs)
603         );
604     }
605
606     return \@sorted_circs;
607 }
608
609
610 sub handle_circ_renew {
611     my $self = shift;
612     my $action = shift;
613     my $ctx = $self->ctx;
614
615     my @renew_ids = $self->cgi->param('circ');
616
617     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
618
619     # TODO: fire off renewal calls in batches to speed things up
620     my @responses;
621     for my $circ (@$circs) {
622
623         my $evt = $U->simplereq(
624             'open-ils.circ', 
625             'open-ils.circ.renew',
626             $self->editor->authtoken,
627             {
628                 patron_id => $self->editor->requestor->id,
629                 copy_id => $circ->{circ}->target_copy,
630                 opac_renewal => 1
631             }
632         );
633
634         # TODO return these, then insert them into the circ data 
635         # blob that is shoved into the template for each circ
636         # so the template won't have to match them
637         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
638     }
639
640     return @responses;
641 }
642
643
644 sub load_myopac_circs {
645     my $self = shift;
646     my $e = $self->editor;
647     my $ctx = $self->ctx;
648
649     $ctx->{circs} = [];
650     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
651     my $offset = $self->cgi->param('offset') || 0;
652     my $action = $self->cgi->param('action') || '';
653
654     # perform the renewal first if necessary
655     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
656
657     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
658
659     my $success_renewals = 0;
660     my $failed_renewals = 0;
661     for my $data (@{$ctx->{circs}}) {
662         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
663
664         if($resp) {
665             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
666             $data->{renewal_response} = $evt;
667             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
668             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
669         }
670     }
671
672     $ctx->{success_renewals} = $success_renewals;
673     $ctx->{failed_renewals} = $failed_renewals;
674
675     return Apache2::Const::OK;
676 }
677
678 sub load_myopac_circ_history {
679     my $self = shift;
680     my $e = $self->editor;
681     my $ctx = $self->ctx;
682     my $limit = $self->cgi->param('limit') || 15;
683     my $offset = $self->cgi->param('offset') || 0;
684
685     $ctx->{circ_history_limit} = $limit;
686     $ctx->{circ_history_offset} = $offset;
687
688     my $circs = $e->json_query({
689         from => ['action.usr_visible_circs', $e->requestor->id],
690         #limit => $limit || 25,
691         #offset => $offset || 0,
692     });
693
694     # XXX: order-by in the json_query above appears to do nothing, so in-query 
695     # paging is not reallly an option.  do the sorting/paging here
696
697     # sort newest to oldest
698     $circs = [ sort { $b->{xact_start} cmp $a->{xact_start} } @$circs ];
699     my @ids = map { $_->{id} } @$circs;
700
701     # find the selected page and trim cruft
702     @ids = @ids[$offset..($offset + $limit - 1)] if $limit;
703     @ids = grep { defined $_ } @ids;
704
705     $ctx->{circs} = $self->fetch_user_circs(1, \@ids);
706     #$ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circs], $limit, $offset);
707
708     return Apache2::Const::OK;
709 }
710
711 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
712 sub load_myopac_hold_history {
713     my $self = shift;
714     my $e = $self->editor;
715     my $ctx = $self->ctx;
716     my $limit = $self->cgi->param('limit') || 15;
717     my $offset = $self->cgi->param('offset') || 0;
718     $ctx->{hold_history_limit} = $limit;
719     $ctx->{hold_history_offset} = $offset;
720
721
722     my $holds = $e->json_query({
723         from => ['action.usr_visible_holds', $e->requestor->id],
724         limit => $limit || 25,
725         offset => $offset || 0
726     });
727
728     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$holds], 0, 1, 0, $limit, $offset);
729
730     return Apache2::Const::OK;
731 }
732
733 sub load_myopac_payment_form {
734     my $self = shift;
735     my $r;
736
737     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact')]) and return $r;
738     $r = $self->prepare_extended_user_info and return $r;
739
740     return Apache2::Const::OK;
741 }
742
743 # TODO: add other filter options as params/configs/etc.
744 sub load_myopac_payments {
745     my $self = shift;
746     my $limit = $self->cgi->param('limit') || 20;
747     my $offset = $self->cgi->param('offset') || 0;
748     my $e = $self->editor;
749
750     $self->ctx->{payment_history_limit} = $limit;
751     $self->ctx->{payment_history_offset} = $offset;
752
753     my $args = {};
754     $args->{limit} = $limit if $limit;
755     $args->{offset} = $offset if $offset;
756
757     $self->ctx->{payments} = $U->simplereq(
758         'open-ils.actor',
759         'open-ils.actor.user.payments.retrieve.atomic',
760         $e->authtoken, $e->requestor->id, $args);
761
762     return Apache2::Const::OK;
763 }
764
765 sub load_myopac_pay {
766     my $self = shift;
767     my $r;
768
769     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact')]) and
770         return $r;
771
772     # balance_owed is computed specifically from the fines we're trying
773     # to pay in this case.
774     if ($self->ctx->{fines}->{balance_owed} <= 0) {
775         $self->apache->log->info(
776             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
777                 join(", ", map(int, $self->cgi->param("xact"))))
778         );
779         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
780     }
781
782     my $cc_args = {"where_process" => 1};
783
784     $cc_args->{$_} = $self->cgi->param($_) for (qw/
785         number cvv2 expire_year expire_month billing_first
786         billing_last billing_address billing_city billing_state
787         billing_zip
788     /);
789
790     my $args = {
791         "cc_args" => $cc_args,
792         "userid" => $self->ctx->{user}->id,
793         "payment_type" => "credit_card_payment",
794         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
795     };
796
797     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
798         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
799     );
800
801     $self->ctx->{"payment_response"} = $resp;
802
803     unless ($resp->{"textcode"}) {
804         $self->ctx->{printable_receipt} = $U->simplereq(
805            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
806            $self->editor->authtoken, $resp->{payments}
807         );
808     }
809
810     return Apache2::Const::OK;
811 }
812
813 sub load_myopac_receipt_print {
814     my $self = shift;
815
816     $self->ctx->{printable_receipt} = $U->simplereq(
817        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
818        $self->editor->authtoken, [$self->cgi->param("payment")]
819     );
820
821     return Apache2::Const::OK;
822 }
823
824 sub load_myopac_receipt_email {
825     my $self = shift;
826
827     # The following ML method doesn't actually check whether the user in
828     # question has an email address, so we do.
829     if ($self->ctx->{user}->email) {
830         $self->ctx->{email_receipt_result} = $U->simplereq(
831            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
832            $self->editor->authtoken, [$self->cgi->param("payment")]
833         );
834     } else {
835         $self->ctx->{email_receipt_result} =
836             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
837     }
838
839     return Apache2::Const::OK;
840 }
841
842 sub prepare_fines {
843     my ($self, $limit, $offset, $id_list) = @_;
844
845     # XXX TODO: check for failure after various network calls
846
847     # It may be unclear, but this result structure lumps circulation and
848     # reservation fines together, and keeps grocery fines separate.
849     $self->ctx->{"fines"} = {
850         "circulation" => [],
851         "grocery" => [],
852         "total_paid" => 0,
853         "total_owed" => 0,
854         "balance_owed" => 0
855     };
856
857     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
858
859     # TODO: This should really be a ML call, but the existing calls 
860     # return an excessive amount of data and don't offer streaming
861
862     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
863
864     my $req = $cstore->request(
865         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
866         {
867             usr => $self->editor->requestor->id,
868             balance_owed => {'!=' => 0},
869             ($id_list && @$id_list ? ("id" => $id_list) : ()),
870         },
871         {
872             flesh => 4,
873             flesh_fields => {
874                 mobts => [qw/grocery circulation reservation/],
875                 bresv => ['target_resource_type'],
876                 brt => ['record'],
877                 mg => ['billings'],
878                 mb => ['btype'],
879                 circ => ['target_copy'],
880                 acp => ['call_number'],
881                 acn => ['record']
882             },
883             order_by => { mobts => 'xact_start' },
884             %paging
885         }
886     );
887
888     my @total_keys = qw/total_paid total_owed balance_owed/;
889     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
890
891     while(my $resp = $req->recv) {
892         my $mobts = $resp->content;
893         my $circ = $mobts->circulation;
894
895         my $last_billing;
896         if($mobts->grocery) {
897             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
898             $last_billing = pop(@billings);
899         }
900
901         # XXX TODO confirm that the following, and the later division by 100.0
902         # to get a floating point representation once again, is sufficiently
903         # "money-safe" math.
904         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
905
906         my $marc_xml = undef;
907         if ($mobts->xact_type eq 'reservation' and
908             $mobts->reservation->target_resource_type->record) {
909             $marc_xml = XML::LibXML->new->parse_string(
910                 $mobts->reservation->target_resource_type->record->marc
911             );
912         } elsif ($mobts->xact_type eq 'circulation' and
913             $circ->target_copy->call_number->id != -1) {
914             $marc_xml = XML::LibXML->new->parse_string(
915                 $circ->target_copy->call_number->record->marc
916             );
917         }
918
919         push(
920             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
921             {
922                 xact => $mobts,
923                 last_grocery_billing => $last_billing,
924                 marc_xml => $marc_xml
925             } 
926         );
927     }
928
929     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
930     return;
931 }
932
933 sub prepare_fines_for_payment {
934     # This assumes $self->prepare_fines has already been run
935     my ($self) = @_;
936
937     my @results = ();
938     if ($self->ctx->{fines}) {
939         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
940             @{$self->ctx->{fines}->{circulation}},
941             @{$self->ctx->{fines}->{grocery}}
942         );
943     }
944
945     return \@results;
946 }
947
948 sub load_myopac_main {
949     my $self = shift;
950     my $limit = $self->cgi->param('limit') || 0;
951     my $offset = $self->cgi->param('offset') || 0;
952
953     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
954 }
955
956 sub load_myopac_update_email {
957     my $self = shift;
958     my $e = $self->editor;
959     my $ctx = $self->ctx;
960     my $email = $self->cgi->param('email') || '';
961
962     return Apache2::Const::OK 
963         unless $self->cgi->request_method eq 'POST';
964
965     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
966         $ctx->{invalid_email} = $email;
967         return Apache2::Const::OK;
968     }
969
970     my $stat = $U->simplereq(
971         'open-ils.actor', 
972         'open-ils.actor.user.email.update', 
973         $e->authtoken, $email);
974
975     my $url = $self->apache->unparsed_uri;
976     $url =~ s/update_email/prefs/;
977
978     return $self->generic_redirect($url);
979 }
980
981 sub load_myopac_update_username {
982     my $self = shift;
983     my $e = $self->editor;
984     my $ctx = $self->ctx;
985     my $username = $self->cgi->param('username') || '';
986
987     return Apache2::Const::OK 
988         unless $self->cgi->request_method eq 'POST';
989
990     unless($username and $username !~ /\s/) { # any other username restrictions?
991         $ctx->{invalid_username} = $username;
992         return Apache2::Const::OK;
993     }
994
995     if($username ne $e->requestor->usrname) {
996
997         my $evt = $U->simplereq(
998             'open-ils.actor', 
999             'open-ils.actor.user.username.update', 
1000             $e->authtoken, $username);
1001
1002         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1003             $ctx->{username_exists} = $username;
1004             return Apache2::Const::OK;
1005         }
1006     }
1007
1008     my $url = $self->apache->unparsed_uri;
1009     $url =~ s/update_username/prefs/;
1010
1011     return $self->generic_redirect($url);
1012 }
1013
1014 sub load_myopac_update_password {
1015     my $self = shift;
1016     my $e = $self->editor;
1017     my $ctx = $self->ctx;
1018
1019     return Apache2::Const::OK 
1020         unless $self->cgi->request_method eq 'POST';
1021
1022     my $current_pw = $self->cgi->param('current_pw') || '';
1023     my $new_pw = $self->cgi->param('new_pw') || '';
1024     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1025
1026     unless($new_pw eq $new_pw2) {
1027         $ctx->{password_nomatch} = 1;
1028         return Apache2::Const::OK;
1029     }
1030
1031     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1032
1033     if($pw_regex and $new_pw !~ /$pw_regex/) {
1034         $ctx->{password_invalid} = 1;
1035         return Apache2::Const::OK;
1036     }
1037
1038     my $evt = $U->simplereq(
1039         'open-ils.actor', 
1040         'open-ils.actor.user.password.update', 
1041         $e->authtoken, $new_pw, $current_pw);
1042
1043
1044     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1045         $ctx->{password_incorrect} = 1;
1046         return Apache2::Const::OK;
1047     }
1048
1049     my $url = $self->apache->unparsed_uri;
1050     $url =~ s/update_password/prefs/;
1051
1052     return $self->generic_redirect($url);
1053 }
1054
1055 sub load_myopac_bookbags {
1056     my $self = shift;
1057     my $e = $self->editor;
1058     my $ctx = $self->ctx;
1059
1060     $e->xact_begin; # replication...
1061
1062     my $rv = $self->load_mylist;
1063     unless($rv eq Apache2::Const::OK) {
1064         $e->rollback;
1065         return $rv;
1066     }
1067
1068     my $args = {
1069         order_by => {cbreb => 'name'},
1070         limit => $self->cgi->param('limit') || 10,
1071         offset => $self->cgi->param('offset') || 0
1072     };
1073
1074     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket([
1075         {owner => $self->editor->requestor->id, btype => 'bookbag'},
1076         # XXX what to do about the possibility of really large bookbags here?
1077         {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
1078     ]);
1079
1080     if(!$ctx->{bookbags}) {
1081         $e->rollback;
1082         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1083     }
1084     
1085     # get unique record IDs
1086     my %rec_ids = ();
1087     foreach my $bbag (@{$ctx->{bookbags}}) {
1088         foreach my $rec_id (
1089             map { $_->target_biblio_record_entry } @{$bbag->items}
1090         ) {
1091             $rec_ids{$rec_id} = 1;
1092         }
1093     }
1094
1095     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
1096
1097     $e->rollback;
1098     return Apache2::Const::OK;
1099 }
1100
1101
1102 # actions are create, delete, show, hide, rename, add_rec, delete_item
1103 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1104 sub load_myopac_bookbag_update {
1105     my ($self, $action, $list_id) = @_;
1106     my $e = $self->editor;
1107     my $cgi = $self->cgi;
1108
1109     $action ||= $cgi->param('action');
1110     $list_id ||= $cgi->param('list');
1111
1112     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1113     my @del_item = $cgi->param('del_item');
1114     my $shared = $cgi->param('shared');
1115     my $name = $cgi->param('name');
1116     my $success = 0;
1117     my $list;
1118
1119     if($action eq 'create') {
1120         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1121         $list->name($name);
1122         $list->owner($e->requestor->id);
1123         $list->btype('bookbag');
1124         $list->pub($shared ? 't' : 'f');
1125         $success = $U->simplereq('open-ils.actor', 
1126             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1127
1128     } else {
1129
1130         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1131
1132         return Apache2::Const::HTTP_BAD_REQUEST unless 
1133             $list and $list->owner == $e->requestor->id;
1134     }
1135
1136     if($action eq 'delete') {
1137         $success = $U->simplereq('open-ils.actor', 
1138             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1139
1140     } elsif($action eq 'show') {
1141         unless($U->is_true($list->pub)) {
1142             $list->pub('t');
1143             $success = $U->simplereq('open-ils.actor', 
1144                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1145         }
1146
1147     } elsif($action eq 'hide') {
1148         if($U->is_true($list->pub)) {
1149             $list->pub('f');
1150             $success = $U->simplereq('open-ils.actor', 
1151                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1152         }
1153
1154     } elsif($action eq 'rename') {
1155         if($name) {
1156             $list->name($name);
1157             $success = $U->simplereq('open-ils.actor', 
1158                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1159         }
1160
1161     } elsif($action eq 'add_rec') {
1162         foreach my $add_rec (@add_rec) {
1163             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1164             $item->bucket($list_id);
1165             $item->target_biblio_record_entry($add_rec);
1166             $success = $U->simplereq('open-ils.actor', 
1167                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1168             last unless $success;
1169         }
1170
1171     } elsif($action eq 'del_item') {
1172         foreach (@del_item) {
1173             $success = $U->simplereq(
1174                 'open-ils.actor',
1175                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1176             );
1177             last unless $success;
1178         }
1179     }
1180
1181     return $self->generic_redirect if $success;
1182
1183     $self->ctx->{bucket_action} = $action;
1184     $self->ctx->{bucket_action_failed} = 1;
1185     return Apache2::Const::OK;
1186 }
1187
1188 1