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