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