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