]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
integrate the new booking.reservation billable transaction table with all the parts...
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Circ.pm
1 package OpenILS::Application::Circ;
2 use OpenILS::Application;
3 use base qw/OpenILS::Application/;
4 use strict; use warnings;
5
6 use OpenILS::Application::Circ::Circulate;
7 use OpenILS::Application::Circ::Survey;
8 use OpenILS::Application::Circ::StatCat;
9 use OpenILS::Application::Circ::Holds;
10 use OpenILS::Application::Circ::HoldNotify;
11 use OpenILS::Application::Circ::Money;
12 use OpenILS::Application::Circ::NonCat;
13 use OpenILS::Application::Circ::CopyLocations;
14 use OpenILS::Application::Circ::CircCommon;
15
16 use DateTime;
17 use DateTime::Format::ISO8601;
18
19 use OpenILS::Application::AppUtils;
20
21 use OpenSRF::Utils qw/:datetime/;
22 use OpenSRF::AppSession;
23 use OpenILS::Utils::ModsParser;
24 use OpenILS::Event;
25 use OpenSRF::EX qw(:try);
26 use OpenSRF::Utils::Logger qw(:logger);
27 use OpenILS::Utils::Fieldmapper;
28 use OpenILS::Utils::Editor;
29 use OpenILS::Utils::CStoreEditor q/:funcs/;
30 use OpenILS::Const qw/:const/;
31 use OpenSRF::Utils::SettingsClient;
32 use OpenILS::Application::Cat::AssetCommon;
33
34 my $apputils = "OpenILS::Application::AppUtils";
35 my $U = $apputils;
36
37
38 # ------------------------------------------------------------------------
39 # Top level Circ package;
40 # ------------------------------------------------------------------------
41
42 sub initialize {
43         my $self = shift;
44         OpenILS::Application::Circ::Circulate->initialize();
45 }
46
47
48 __PACKAGE__->register_method(
49         method => 'retrieve_circ',
50         api_name        => 'open-ils.circ.retrieve',
51         signature => q/
52                 Retrieve a circ object by id
53                 @param authtoken Login session key
54                 @pararm circid The id of the circ object
55         /
56 );
57 sub retrieve_circ {
58         my( $s, $c, $a, $i ) = @_;
59         my $e = new_editor(authtoken => $a);
60         return $e->event unless $e->checkauth;
61         my $circ = $e->retrieve_action_circulation($i) or return $e->event;
62         if( $e->requestor->id ne $circ->usr ) {
63                 return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
64         }
65         return $circ;
66 }
67
68
69 __PACKAGE__->register_method(
70         method => 'fetch_circ_mods',
71         api_name => 'open-ils.circ.circ_modifier.retrieve.all');
72 sub fetch_circ_mods {
73     my($self, $conn, $args) = @_;
74     my $mods = new_editor()->retrieve_all_config_circ_modifier;
75     return [ map {$_->code} @$mods ] unless $$args{full};
76     return $mods;
77 }
78
79 __PACKAGE__->register_method(
80         method => 'fetch_bill_types',
81         api_name => 'open-ils.circ.billing_type.retrieve.all');
82 sub fetch_bill_types {
83         my $conf = OpenSRF::Utils::SettingsClient->new;
84         return $conf->config_value(
85                 'apps', 'open-ils.circ', 'app_settings', 'billing_types', 'type' );
86 }
87
88
89 __PACKAGE__->register_method(
90     method => 'ranged_billing_types',
91     api_name => 'open-ils.circ.billing_type.ranged.retrieve.all');
92
93 sub ranged_billing_types {
94     my($self, $conn, $auth, $org_id, $depth) = @_;
95     my $e = new_editor(authtoken => $auth);
96     return $e->event unless $e->checkauth;
97     return $e->event unless $e->allowed('VIEW_BILLING_TYPE', $org_id);
98     return $e->search_config_billing_type(
99         {owner => $U->get_org_full_path($org_id, $depth)});
100 }
101
102
103
104 # ------------------------------------------------------------------------
105 # Returns an array of {circ, record} hashes checked out by the user.
106 # ------------------------------------------------------------------------
107 __PACKAGE__->register_method(
108         method  => "checkouts_by_user",
109         api_name        => "open-ils.circ.actor.user.checked_out",
110     stream => 1,
111         NOTES           => <<"  NOTES");
112         Returns a list of open circulations as a pile of objects.  Each object
113         contains the relevant copy, circ, and record
114         NOTES
115
116 sub checkouts_by_user {
117         my($self, $client, $auth, $user_id) = @_;
118
119     my $e = new_editor(authtoken=>$auth);
120     return $e->event unless $e->checkauth;
121
122         my $circ_ids = $e->search_action_circulation(
123         {   usr => $user_id,
124             checkin_time => undef,
125             '-or' => [
126                 {stop_fines => undef},
127                 {stop_fines => ['MAXFINES','LONGOVERDUE']}
128             ]
129         },
130         {idlist => 1}
131     );
132
133     for my $id (@$circ_ids) {
134         my $circ = $e->retrieve_action_circulation([
135             $id,
136             {   flesh => 3,
137                 flesh_fields => {
138                     circ => ['target_copy'],
139                     acp => ['call_number'],
140                     acn => ['record']
141                 }
142             }
143         ]);
144
145         # un-flesh for consistency
146         my $c = $circ->target_copy;
147         $circ->target_copy($c->id);
148
149         my $cn = $c->call_number;
150         $c->call_number($cn->id);
151
152         my $t = $cn->record;
153         $cn->record($t->id);
154
155         $client->respond(
156             {   circ => $circ,
157                 copy => $c,
158                 record => $U->record_to_mvr($t)
159             }
160         );
161     }
162
163     return undef;
164 }
165
166
167
168 __PACKAGE__->register_method(
169         method  => "checkouts_by_user_slim",
170         api_name        => "open-ils.circ.actor.user.checked_out.slim",
171         NOTES           => <<"  NOTES");
172         Returns a list of open circulation objects
173         NOTES
174
175 # DEPRECAT ME?? XXX
176 sub checkouts_by_user_slim {
177         my( $self, $client, $user_session, $user_id ) = @_;
178
179         my( $requestor, $target, $copy, $record, $evt );
180
181         ( $requestor, $target, $evt ) = 
182                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
183         return $evt if $evt;
184
185         $logger->debug( 'User ' . $requestor->id . 
186                 " retrieving checked out items for user " . $target->id );
187
188         # XXX Make the call correct..
189         return $apputils->simplereq(
190                 'open-ils.cstore',
191                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
192                 { usr => $target->id, checkin_time => undef } );
193 #               { usr => $target->id } );
194 }
195
196
197 __PACKAGE__->register_method(
198         method  => "checkouts_by_user_opac",
199         api_name        => "open-ils.circ.actor.user.checked_out.opac",);
200
201 # XXX Deprecate Me
202 sub checkouts_by_user_opac {
203         my( $self, $client, $auth, $user_id ) = @_;
204
205         my $e = OpenILS::Utils::Editor->new( authtoken => $auth );
206         return $e->event unless $e->checkauth;
207         $user_id ||= $e->requestor->id;
208         return $e->event unless 
209                 my $patron = $e->retrieve_actor_user($user_id);
210
211         my $data;
212         my $search = {usr => $user_id, stop_fines => undef};
213
214         if( $user_id ne $e->requestor->id ) {
215                 $data = $e->search_action_circulation(
216                         $search, {checkperm=>1, permorg=>$patron->home_ou})
217                         or return $e->event;
218
219         } else {
220                 $data = $e->search_action_circulation($search);
221         }
222
223         return $data;
224 }
225
226
227 __PACKAGE__->register_method(
228         method  => "title_from_transaction",
229         api_name        => "open-ils.circ.circ_transaction.find_title",
230         NOTES           => <<"  NOTES");
231         Returns a mods object for the title that is linked to from the 
232         copy from the hold that created the given transaction
233         NOTES
234
235 sub title_from_transaction {
236         my( $self, $client, $login_session, $transactionid ) = @_;
237
238         my( $user, $circ, $title, $evt );
239
240         ( $user, $evt ) = $apputils->checkses( $login_session );
241         return $evt if $evt;
242
243         ( $circ, $evt ) = $apputils->fetch_circulation($transactionid);
244         return $evt if $evt;
245         
246         ($title, $evt) = $apputils->fetch_record_by_copy($circ->target_copy);
247         return $evt if $evt;
248
249         return $apputils->record_to_mvr($title);
250 }
251
252
253
254 __PACKAGE__->register_method(
255         method  => "new_set_circ_lost",
256         api_name        => "open-ils.circ.circulation.set_lost",
257         signature       => q/
258         Sets the copy and related open circulation to lost
259                 @param auth
260                 @param args : barcode
261         /
262 );
263
264
265 # ---------------------------------------------------------------------
266 # Sets a circulation to lost.  updates copy status to lost
267 # applies copy and/or prcoessing fees depending on org settings
268 # ---------------------------------------------------------------------
269 sub new_set_circ_lost {
270     my( $self, $conn, $auth, $args ) = @_;
271
272     my $e = new_editor(authtoken=>$auth, xact=>1);
273     return $e->die_event unless $e->checkauth;
274
275     my $copy = $e->search_asset_copy({barcode=>$$args{barcode}, deleted=>'f'})->[0]
276         or return $e->die_event;
277
278     my $evt = OpenILS::Application::Cat::AssetCommon->set_item_lost($e, $copy->id);
279     return $evt if $evt;
280
281     $e->commit;
282     return 1;
283 }
284
285
286 __PACKAGE__->register_method(
287         method  => "set_circ_claims_returned",
288         api_name        => "open-ils.circ.circulation.set_claims_returned",
289         signature => {
290         desc => q/Sets the circ for a given item as claims returned
291                 If a backdate is provided, overdue fines will be voided
292                 back to the backdate/,
293         params => [
294             {desc => 'Authentication token', type => 'string'},
295             {desc => 'Arguments, including "barcode" and optional "backdate"', type => 'object'}
296         ],
297         return => {desc => q/1 on success, failure event on error, and 
298             PATRON_EXCEEDS_CLAIMS_RETURN_COUNT if the patron exceeds the 
299             configured claims return maximum/}
300     }
301 );
302
303 __PACKAGE__->register_method(
304         method  => "set_circ_claims_returned",
305         api_name        => "open-ils.circ.circulation.set_claims_returned.override",
306         signature => {
307         desc => q/This adds support for overrideing the configured max 
308                 claims returned amount. 
309                 @see open-ils.circ.circulation.set_claims_returned./,
310     }
311 );
312
313 sub set_circ_claims_returned {
314     my( $self, $conn, $auth, $args ) = @_;
315
316     my $e = new_editor(authtoken=>$auth, xact=>1);
317     return $e->die_event unless $e->checkauth;
318
319     my $barcode = $$args{barcode};
320     my $backdate = $$args{backdate};
321
322     my $copy = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'})->[0] 
323         or return $e->die_event;
324
325     my $circ = $e->search_action_circulation(
326         {checkin_time => undef, target_copy => $copy->id})->[0]
327             or return $e->die_event;
328
329     $backdate = $circ->due_date if $$args{use_due_date};
330
331     $logger->info("marking circ for item $barcode as claims returned".
332         (($backdate) ? " with backdate $backdate" : ''));
333
334     my $patron = $e->retrieve_actor_user($circ->usr);
335     my $max_count = $U->ou_ancestor_setting_value(
336         $circ->circ_lib, 'circ.max_patron_claim_return_count', $e);
337
338     # If the patron has too instances of many claims returned, 
339     # require an override to continue.  A configured max of 
340     # 0 means all attempts require an override
341     if(defined $max_count and $patron->claims_returned_count >= $max_count) {
342
343         if($self->api_name =~ /override/) {
344
345             # see if we're allowed to override
346             return $e->die_event unless 
347                 $e->allowed('SET_CIRC_CLAIMS_RETURNED.override', $circ->circ_lib);
348
349         } else {
350
351             # exit early and return the max claims return event
352             $e->rollback;
353             return OpenILS::Event->new(
354                 'PATRON_EXCEEDS_CLAIMS_RETURN_COUNT', 
355                 payload => {
356                     patron_count => $patron->claims_returned_count,
357                     max_count => $max_count
358                 }
359             );
360         }
361     }
362
363     $e->allowed('SET_CIRC_CLAIMS_RETURNED', $circ->circ_lib) 
364         or return $e->die_event;
365
366     $circ->stop_fines(OILS_STOP_FINES_CLAIMSRETURNED);
367         $circ->stop_fines_time('now') unless $circ->stop_fines_time;
368
369     if( $backdate ) {
370         # make it look like the circ stopped at the cliams returned time
371         $circ->stop_fines_time(clense_ISO8601($backdate));
372         my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
373         return $evt if $evt;
374     }
375
376     $e->update_action_circulation($circ) or return $e->die_event;
377
378     # see if there is a configured post-claims-return copy status
379     if(my $stat = $U->ou_ancestor_setting_value($circ->circ_lib, 'circ.claim_return.copy_status')) {
380             $copy->status($stat);
381             $copy->edit_date('now');
382             $copy->editor($e->requestor->id);
383             $e->update_asset_copy($copy) or return $e->die_event;
384     }
385
386     $e->commit;
387     return 1;
388 }
389
390
391 __PACKAGE__->register_method(
392         method  => "post_checkin_backdate_circ",
393         api_name        => "open-ils.circ.post_checkin_backdate",
394         signature => {
395         desc => q/Back-date an already checked in circulation/,
396         params => [
397             {desc => 'Authentication token', type => 'string'},
398             {desc => 'Circ ID', type => 'number'},
399             {desc => 'ISO8601 backdate', type => 'string'},
400         ],
401         return => {desc => q/1 on success, failure event on error/}
402     }
403 );
404
405 __PACKAGE__->register_method(
406         method  => "post_checkin_backdate_circ",
407         api_name        => "open-ils.circ.post_checkin_backdate.batch",
408     stream => 1,
409         signature => {
410         desc => q/@see open-ils.circ.post_checkin_backdate.  Batch mode/,
411         params => [
412             {desc => 'Authentication token', type => 'string'},
413             {desc => 'List of Circ ID', type => 'array'},
414             {desc => 'ISO8601 backdate', type => 'string'},
415         ],
416         return => {desc => q/Set of: 1 on success, failure event on error/}
417     }
418 );
419
420
421 sub post_checkin_backdate_circ {
422     my( $self, $conn, $auth, $circ_id, $backdate ) = @_;
423     my $e = new_editor(authtoken=>$auth);
424     return $e->die_event unless $e->checkauth;
425     if($self->api_name =~ /batch/) {
426         foreach my $c (@$circ_id) {
427             $conn->respond(post_checkin_backdate_circ_impl($e, $c, $backdate));
428         }
429     } else {
430         $conn->respond_complete(post_checkin_backdate_circ_impl($e, $circ_id, $backdate));
431     }
432
433     $e->disconnect;
434     return undef;
435 }
436
437
438 sub post_checkin_backdate_circ_impl {
439     my($e, $circ_id, $backdate) = @_;
440
441     $e->xact_begin;
442
443     my $circ = $e->retrieve_action_circulation($circ_id)
444         or return $e->die_event;
445
446     # anyone with checkin perms can backdate (more restrictive?)
447     return $e->die_event unless $e->allowed('COPY_CHECKIN', $circ->circ_lib);
448
449     # don't allow back-dating an open circulation
450     return OpenILS::Event->new('BAD_PARAMS') unless 
451         $backdate and $circ->checkin_time;
452
453     # update the checkin and stop_fines times to reflect the new backdate
454     $circ->stop_fines_time(clense_ISO8601($backdate));
455     $circ->checkin_time(clense_ISO8601($backdate));
456     $e->update_action_circulation($circ) or return $e->die_event;
457
458     # now void the overdues "erased" by the back-dating
459     my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
460     return $evt if $evt;
461
462     # If the circ was closed before and the balance owned !=0, re-open the transaction
463     $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
464     return $evt if $evt;
465
466     $e->xact_commit;
467     return 1;
468 }
469
470
471
472 __PACKAGE__->register_method (
473         method          => 'set_circ_due_date',
474         api_name                => 'open-ils.circ.circulation.due_date.update',
475         signature       => q/
476                 Updates the due_date on the given circ
477                 @param authtoken
478                 @param circid The id of the circ to update
479                 @param date The timestamp of the new due date
480         /
481 );
482
483 sub set_circ_due_date {
484         my( $self, $conn, $auth, $circ_id, $date ) = @_;
485
486     my $e = new_editor(xact=>1, authtoken=>$auth);
487     return $e->die_event unless $e->checkauth;
488     my $circ = $e->retrieve_action_circulation($circ_id)
489         or return $e->die_event;
490
491     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
492         $date = clense_ISO8601($date);
493         $circ->due_date($date);
494     $e->update_action_circulation($circ) or return $e->die_event;
495     $e->commit;
496
497     return $circ->id;
498 }
499
500
501 __PACKAGE__->register_method(
502         method          => "create_in_house_use",
503         api_name                => 'open-ils.circ.in_house_use.create',
504         signature       =>      q/
505                 Creates an in-house use action.
506                 @param $authtoken The login session key
507                 @param params A hash of params including
508                         'location' The org unit id where the in-house use occurs
509                         'copyid' The copy in question
510                         'count' The number of in-house uses to apply to this copy
511                 @return An array of id's representing the id's of the newly created
512                 in-house use objects or an event on an error
513         /);
514
515 __PACKAGE__->register_method(
516         method          => "create_in_house_use",
517         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
518 );
519
520
521 sub create_in_house_use {
522         my( $self, $client, $auth, $params ) = @_;
523
524         my( $evt, $copy );
525         my $org                 = $params->{location};
526         my $copyid              = $params->{copyid};
527         my $count               = $params->{count} || 1;
528         my $nc_type             = $params->{non_cat_type};
529         my $use_time    = $params->{use_time} || 'now';
530
531         my $e = new_editor(xact=>1,authtoken=>$auth);
532         return $e->event unless $e->checkauth;
533         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
534
535         my $non_cat = 1 if $self->api_name =~ /non_cat/;
536
537         unless( $non_cat ) {
538                 if( $copyid ) {
539                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
540                 } else {
541                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
542                                 or return $e->event;
543                         $copyid = $copy->id;
544                 }
545         }
546
547         if( $use_time ne 'now' ) {
548                 $use_time = clense_ISO8601($use_time);
549                 $logger->debug("in_house_use setting use time to $use_time");
550         }
551
552         my @ids;
553         for(1..$count) {
554
555                 my $ihu;
556                 my $method;
557                 my $cmeth;
558
559                 if($non_cat) {
560                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
561                         $ihu->item_type($nc_type);
562                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
563                         $cmeth = "create_action_non_cat_in_house_use";
564
565                 } else {
566                         $ihu = Fieldmapper::action::in_house_use->new;
567                         $ihu->item($copyid);
568                         $method = 'open-ils.storage.direct.action.in_house_use.create';
569                         $cmeth = "create_action_in_house_use";
570                 }
571
572                 $ihu->staff($e->requestor->id);
573                 $ihu->org_unit($org);
574                 $ihu->use_time($use_time);
575
576                 $ihu = $e->$cmeth($ihu) or return $e->event;
577                 push( @ids, $ihu->id );
578         }
579
580         $e->commit;
581         return \@ids;
582 }
583
584
585
586
587
588 __PACKAGE__->register_method(
589         method  => "view_circs",
590         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
591         notes           => q/
592                 Retrieves the last X circs for a given copy
593                 @param authtoken The login session key
594                 @param copyid The copy to check
595                 @param count How far to go back in the item history
596                 @return An array of circ ids
597         /);
598
599 # ----------------------------------------------------------------------
600 # Returns $count most recent circs.  If count exceeds the configured 
601 # max, use the configured max instead
602 # ----------------------------------------------------------------------
603 sub view_circs {
604         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
605
606     my $e = new_editor(authtoken => $authtoken);
607     return $e->event unless $e->checkauth;
608     
609     my $copy = $e->retrieve_asset_copy([
610         $copyid,
611         {   flesh => 1,
612             flesh_fields => {acp => ['call_number']}
613         }
614     ]) or return $e->event;
615
616     return $e->event unless $e->allowed(
617         'VIEW_COPY_CHECKOUT_HISTORY', 
618         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
619             $copy->circ_lib : $copy->call_number->owning_lib);
620         
621     my $max_history = $U->ou_ancestor_setting_value(
622         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
623
624     if(defined $max_history) {
625         $count = $max_history unless defined $count and $count < $max_history;
626     } else {
627         $count = 4 unless defined $count;
628     }
629
630     return $e->search_action_circulation([
631         {target_copy => $copyid}, 
632         {limit => $count, order_by => { circ => "xact_start DESC" }} 
633     ]);
634 }
635
636
637 __PACKAGE__->register_method(
638         method  => "circ_count",
639         api_name        => "open-ils.circ.circulation.count",
640         notes           => q/
641                 Returns the number of times the item has circulated
642                 @param copyid The copy to check
643         /);
644
645 sub circ_count {
646         my( $self, $client, $copyid, $range ) = @_; 
647         my $e = OpenILS::Utils::Editor->new;
648         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
649 }
650
651
652
653 __PACKAGE__->register_method(
654         method          => 'fetch_notes',
655         api_name                => 'open-ils.circ.copy_note.retrieve.all',
656         signature       => q/
657                 Returns an array of copy note objects.  
658                 @param args A named hash of parameters including:
659                         authtoken       : Required if viewing non-public notes
660                         itemid          : The id of the item whose notes we want to retrieve
661                         pub                     : True if all the caller wants are public notes
662                 @return An array of note objects
663         /);
664
665 __PACKAGE__->register_method(
666         method          => 'fetch_notes',
667         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
668         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
669
670 __PACKAGE__->register_method(
671         method          => 'fetch_notes',
672         api_name                => 'open-ils.circ.title_note.retrieve.all',
673         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
674
675
676 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
677 sub fetch_notes {
678         my( $self, $connection, $args ) = @_;
679
680         my $id = $$args{itemid};
681         my $authtoken = $$args{authtoken};
682         my( $r, $evt);
683
684         if( $self->api_name =~ /copy/ ) {
685                 if( $$args{pub} ) {
686                         return $U->cstorereq(
687                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
688                                 { owning_copy => $id, pub => 't' } );
689                 } else {
690                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
691                         return $evt if $evt;
692                         return $U->cstorereq(
693                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
694                 }
695
696         } elsif( $self->api_name =~ /call_number/ ) {
697                 if( $$args{pub} ) {
698                         return $U->cstorereq(
699                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
700                                 { call_number => $id, pub => 't' } );
701                 } else {
702                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
703                         return $evt if $evt;
704                         return $U->cstorereq(
705                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
706                 }
707
708         } elsif( $self->api_name =~ /title/ ) {
709                 if( $$args{pub} ) {
710                         return $U->cstorereq(
711                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
712                                 { record => $id, pub => 't' } );
713                 } else {
714                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
715                         return $evt if $evt;
716                         return $U->cstorereq(
717                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
718                 }
719         }
720
721         return undef;
722 }
723
724 __PACKAGE__->register_method(
725         method  => 'has_notes',
726         api_name        => 'open-ils.circ.copy.has_notes');
727 __PACKAGE__->register_method(
728         method  => 'has_notes',
729         api_name        => 'open-ils.circ.call_number.has_notes');
730 __PACKAGE__->register_method(
731         method  => 'has_notes',
732         api_name        => 'open-ils.circ.title.has_notes');
733
734
735 sub has_notes {
736         my( $self, $conn, $authtoken, $id ) = @_;
737         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
738         return $editor->event unless $editor->checkauth;
739
740         my $n = $editor->search_asset_copy_note(
741                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
742
743         $n = $editor->search_asset_call_number_note(
744                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
745
746         $n = $editor->search_biblio_record_note(
747                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
748
749         return scalar @$n;
750 }
751
752
753
754 __PACKAGE__->register_method(
755         method          => 'create_copy_note',
756         api_name                => 'open-ils.circ.copy_note.create',
757         signature       => q/
758                 Creates a new copy note
759                 @param authtoken The login session key
760                 @param note     The note object to create
761                 @return The id of the new note object
762         /);
763
764 sub create_copy_note {
765         my( $self, $connection, $authtoken, $note ) = @_;
766
767         my $e = new_editor(xact=>1, authtoken=>$authtoken);
768         return $e->event unless $e->checkauth;
769         my $copy = $e->retrieve_asset_copy(
770                 [
771                         $note->owning_copy,
772                         {       flesh => 1,
773                                 flesh_fields => { 'acp' => ['call_number'] }
774                         }
775                 ]
776         );
777
778         return $e->event unless 
779                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
780
781         $note->create_date('now');
782         $note->creator($e->requestor->id);
783         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
784         $note->clear_id;
785
786         $e->create_asset_copy_note($note) or return $e->event;
787         $e->commit;
788         return $note->id;
789 }
790
791
792 __PACKAGE__->register_method(
793         method          => 'delete_copy_note',
794         api_name                =>      'open-ils.circ.copy_note.delete',
795         signature       => q/
796                 Deletes an existing copy note
797                 @param authtoken The login session key
798                 @param noteid The id of the note to delete
799                 @return 1 on success - Event otherwise.
800                 /);
801 sub delete_copy_note {
802         my( $self, $conn, $authtoken, $noteid ) = @_;
803
804         my $e = new_editor(xact=>1, authtoken=>$authtoken);
805         return $e->die_event unless $e->checkauth;
806
807         my $note = $e->retrieve_asset_copy_note([
808                 $noteid,
809                 { flesh => 2,
810                         flesh_fields => {
811                                 'acpn' => [ 'owning_copy' ],
812                                 'acp' => [ 'call_number' ],
813                         }
814                 }
815         ]) or return $e->die_event;
816
817         if( $note->creator ne $e->requestor->id ) {
818                 return $e->die_event unless 
819                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
820         }
821
822         $e->delete_asset_copy_note($note) or return $e->die_event;
823         $e->commit;
824         return 1;
825 }
826
827
828 __PACKAGE__->register_method(
829         method => 'age_hold_rules',
830         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
831 );
832
833 sub age_hold_rules {
834         my( $self, $conn ) = @_;
835         return new_editor()->retrieve_all_config_rules_age_hold_protect();
836 }
837
838
839
840 __PACKAGE__->register_method(
841         method => 'copy_details_barcode',
842     authoritative => 1,
843         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
844 sub copy_details_barcode {
845         my( $self, $conn, $auth, $barcode ) = @_;
846     my $e = new_editor();
847     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
848     return $e->event unless $cid;
849         return copy_details( $self, $conn, $auth, $cid );
850 }
851
852
853 __PACKAGE__->register_method(
854         method => 'copy_details',
855         api_name => 'open-ils.circ.copy_details.retrieve');
856
857 sub copy_details {
858         my( $self, $conn, $auth, $copy_id ) = @_;
859         my $e = new_editor(authtoken=>$auth);
860         return $e->event unless $e->checkauth;
861
862         my $flesh = { flesh => 1 };
863
864         my $copy = $e->retrieve_asset_copy(
865                 [
866                         $copy_id,
867                         {
868                                 flesh => 2,
869                                 flesh_fields => {
870                                         acp => ['call_number'],
871                                         acn => ['record']
872                                 }
873                         }
874                 ]) or return $e->event;
875
876
877         # De-flesh the copy for backwards compatibility
878         my $mvr;
879         my $vol = $copy->call_number;
880         if( ref $vol ) {
881                 $copy->call_number($vol->id);
882                 my $record = $vol->record;
883                 if( ref $record ) {
884                         $vol->record($record->id);
885                         $mvr = $U->record_to_mvr($record);
886                 }
887         }
888
889
890         my $hold = $e->search_action_hold_request(
891                 { 
892                         current_copy            => $copy_id, 
893                         capture_time            => { "!=" => undef },
894                         fulfillment_time        => undef,
895                         cancel_time                     => undef,
896                 }
897         )->[0];
898
899         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
900
901         my $transit = $e->search_action_transit_copy(
902                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
903
904         # find the latest circ, open or closed
905         my $circ = $e->search_action_circulation(
906                 [
907                         { target_copy => $copy_id },
908                         { 
909                 flesh => 1,
910                 flesh_fields => {
911                     circ => [
912                         'workstation',
913                         'checkin_workstation', 
914                         'duration_rule', 
915                         'max_fine_rule', 
916                         'recurring_fine_rule'
917                     ]
918                 },
919                 order_by => { circ => 'xact_start desc' }, 
920                 limit => 1 
921             }
922                 ]
923         )->[0];
924
925
926         return {
927                 copy            => $copy,
928                 hold            => $hold,
929                 transit => $transit,
930                 circ            => $circ,
931                 volume  => $vol,
932                 mvr             => $mvr,
933         };
934 }
935
936
937
938
939 __PACKAGE__->register_method(
940         method => 'mark_item',
941         api_name => 'open-ils.circ.mark_item_damaged',
942         signature       => q/
943                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
944                 @param authtoken The login session key
945                 @param copy_id The ID of the copy to mark as damaged
946                 @return 1 on success - Event otherwise.
947                 /
948 );
949 __PACKAGE__->register_method(
950         method => 'mark_item',
951         api_name => 'open-ils.circ.mark_item_missing',
952         signature       => q/
953                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
954                 @param authtoken The login session key
955                 @param copy_id The ID of the copy to mark as missing 
956                 @return 1 on success - Event otherwise.
957                 /
958 );
959 __PACKAGE__->register_method(
960         method => 'mark_item',
961         api_name => 'open-ils.circ.mark_item_bindery',
962         signature       => q/
963                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
964                 @param authtoken The login session key
965                 @param copy_id The ID of the copy to mark as bindery
966                 @return 1 on success - Event otherwise.
967                 /
968 );
969 __PACKAGE__->register_method(
970         method => 'mark_item',
971         api_name => 'open-ils.circ.mark_item_on_order',
972         signature       => q/
973                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
974                 @param authtoken The login session key
975                 @param copy_id The ID of the copy to mark as on order 
976                 @return 1 on success - Event otherwise.
977                 /
978 );
979 __PACKAGE__->register_method(
980         method => 'mark_item',
981         api_name => 'open-ils.circ.mark_item_ill',
982         signature       => q/
983                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
984                 @param authtoken The login session key
985                 @param copy_id The ID of the copy to mark as inter-library loan
986                 @return 1 on success - Event otherwise.
987                 /
988 );
989 __PACKAGE__->register_method(
990         method => 'mark_item',
991         api_name => 'open-ils.circ.mark_item_cataloging',
992         signature       => q/
993                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
994                 @param authtoken The login session key
995                 @param copy_id The ID of the copy to mark as cataloging 
996                 @return 1 on success - Event otherwise.
997                 /
998 );
999 __PACKAGE__->register_method(
1000         method => 'mark_item',
1001         api_name => 'open-ils.circ.mark_item_reserves',
1002         signature       => q/
1003                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
1004                 @param authtoken The login session key
1005                 @param copy_id The ID of the copy to mark as reserves
1006                 @return 1 on success - Event otherwise.
1007                 /
1008 );
1009 __PACKAGE__->register_method(
1010         method => 'mark_item',
1011         api_name => 'open-ils.circ.mark_item_discard',
1012         signature       => q/
1013                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
1014                 @param authtoken The login session key
1015                 @param copy_id The ID of the copy to mark as discard
1016                 @return 1 on success - Event otherwise.
1017                 /
1018 );
1019
1020 sub mark_item {
1021         my( $self, $conn, $auth, $copy_id, $args ) = @_;
1022         my $e = new_editor(authtoken=>$auth, xact =>1);
1023         return $e->die_event unless $e->checkauth;
1024     $args ||= {};
1025
1026     my $copy = $e->retrieve_asset_copy([
1027         $copy_id,
1028         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
1029             or return $e->die_event;
1030
1031     my $owning_lib = 
1032         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
1033             $copy->circ_lib : $copy->call_number->owning_lib;
1034
1035     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
1036
1037
1038         my $perm = 'MARK_ITEM_MISSING';
1039         my $stat = OILS_COPY_STATUS_MISSING;
1040
1041         if( $self->api_name =~ /damaged/ ) {
1042                 $perm = 'MARK_ITEM_DAMAGED';
1043                 $stat = OILS_COPY_STATUS_DAMAGED;
1044         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
1045         return $evt if $evt;
1046
1047         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1048         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
1049
1050         } elsif ( $self->api_name =~ /bindery/ ) {
1051                 $perm = 'MARK_ITEM_BINDERY';
1052                 $stat = OILS_COPY_STATUS_BINDERY;
1053         } elsif ( $self->api_name =~ /on_order/ ) {
1054                 $perm = 'MARK_ITEM_ON_ORDER';
1055                 $stat = OILS_COPY_STATUS_ON_ORDER;
1056         } elsif ( $self->api_name =~ /ill/ ) {
1057                 $perm = 'MARK_ITEM_ILL';
1058                 $stat = OILS_COPY_STATUS_ILL;
1059         } elsif ( $self->api_name =~ /cataloging/ ) {
1060                 $perm = 'MARK_ITEM_CATALOGING';
1061                 $stat = OILS_COPY_STATUS_CATALOGING;
1062         } elsif ( $self->api_name =~ /reserves/ ) {
1063                 $perm = 'MARK_ITEM_RESERVES';
1064                 $stat = OILS_COPY_STATUS_RESERVES;
1065         } elsif ( $self->api_name =~ /discard/ ) {
1066                 $perm = 'MARK_ITEM_DISCARD';
1067                 $stat = OILS_COPY_STATUS_DISCARD;
1068         }
1069
1070
1071         $copy->status($stat);
1072         $copy->edit_date('now');
1073         $copy->editor($e->requestor->id);
1074
1075         $e->update_asset_copy($copy) or return $e->die_event;
1076
1077         my $holds = $e->search_action_hold_request(
1078                 { 
1079                         current_copy => $copy->id,
1080                         fulfillment_time => undef,
1081                         cancel_time => undef,
1082                 }
1083         );
1084
1085         $e->commit;
1086
1087         $logger->debug("resetting holds that target the marked copy");
1088         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
1089
1090         return 1;
1091 }
1092
1093 sub handle_mark_damaged {
1094     my($e, $copy, $owning_lib, $args) = @_;
1095
1096     my $apply = $args->{apply_fines} || '';
1097     return undef if $apply eq 'noapply';
1098
1099     my $new_amount = $args->{override_amount};
1100     my $new_btype = $args->{override_btype};
1101     my $new_note = $args->{override_note};
1102
1103     # grab the last circulation
1104     my $circ = $e->search_action_circulation([
1105         {   target_copy => $copy->id}, 
1106         {   limit => 1, 
1107             order_by => {circ => "xact_start DESC"},
1108             flesh => 2,
1109             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
1110         }
1111     ])->[0];
1112
1113     return undef unless $circ;
1114
1115     my $charge_price = $U->ou_ancestor_setting_value(
1116         $owning_lib, 'circ.charge_on_damaged', $e);
1117
1118     my $proc_fee = $U->ou_ancestor_setting_value(
1119         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1120
1121     my $void_overdue = $U->ou_ancestor_setting_value(
1122         $owning_lib, 'circ.damaged.void_ovedue', $e) || 0;
1123
1124     return undef unless $charge_price or $proc_fee;
1125
1126     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1127     my $total = $copy_price + $proc_fee;
1128
1129     if($apply) {
1130         
1131         if($new_amount and $new_btype) {
1132
1133             # Allow staff to override the amount to charge for a damaged item
1134             # Consider the case where the item is only partially damaged
1135             # This value is meant to take the place of the item price and
1136             # optional processing fee.
1137
1138             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1139                 $e, $new_amount, $new_btype, 'Damaged Item Override', $circ->id, $new_note);
1140             return $evt if $evt;
1141
1142         } else {
1143
1144             if($charge_price and $copy_price) {
1145                 my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1146                     $e, $copy_price, 7, 'Damaged Item', $circ->id);
1147                 return $evt if $evt;
1148             }
1149
1150             if($proc_fee) {
1151                 my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1152                     $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1153                 return $evt if $evt;
1154             }
1155         }
1156
1157         # the assumption is that you would not void the overdues unless you 
1158         # were also charging for the item and/or applying a processing fee
1159         if($void_overdue) {
1160             my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ);
1161             return $evt if $evt;
1162         }
1163
1164         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1165         return $evt if $evt;
1166
1167         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1168         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1169
1170         return undef;
1171
1172     } else {
1173         return OpenILS::Event->new('DAMAGE_CHARGE', 
1174             payload => {
1175                 circ => $circ,
1176                 charge => $total
1177             }
1178         );
1179     }
1180 }
1181
1182
1183
1184
1185
1186
1187 # ----------------------------------------------------------------------
1188 __PACKAGE__->register_method(
1189         method => 'magic_fetch',
1190         api_name => 'open-ils.agent.fetch'
1191 );
1192
1193 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1194
1195 sub magic_fetch {
1196         my( $self, $conn, $auth, $args ) = @_;
1197         my $e = new_editor( authtoken => $auth );
1198         return $e->event unless $e->checkauth;
1199
1200         my $hint = $$args{hint};
1201         my $id  = $$args{id};
1202
1203         # Is the call allowed to fetch this type of object?
1204         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1205
1206         # Find the class the implements the given hint
1207         my ($class) = grep { 
1208                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1209
1210         $class =~ s/Fieldmapper:://og;
1211         $class =~ s/::/_/og;
1212         my $method = "retrieve_$class";
1213
1214         my $obj = $e->$method($id) or return $e->event;
1215         return $obj;
1216 }
1217 # ----------------------------------------------------------------------
1218
1219
1220 __PACKAGE__->register_method(
1221         method  => "fleshed_circ_retrieve",
1222     authoritative => 1,
1223         api_name        => "open-ils.circ.fleshed.retrieve",);
1224
1225 sub fleshed_circ_retrieve {
1226         my( $self, $client, $id ) = @_;
1227         my $e = new_editor();
1228         my $circ = $e->retrieve_action_circulation(
1229                 [
1230                         $id,
1231                         { 
1232                                 flesh                           => 4,
1233                                 flesh_fields    => { 
1234                                         circ => [ qw/ target_copy / ],
1235                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1236                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1237                                         acn => [ qw/ record / ],
1238                                 }
1239                         }
1240                 ]
1241         ) or return $e->event;
1242         
1243         my $copy = $circ->target_copy;
1244         my $vol = $copy->call_number;
1245         my $rec = $circ->target_copy->call_number->record;
1246
1247         $vol->record($rec->id);
1248         $copy->call_number($vol->id);
1249         $circ->target_copy($copy->id);
1250
1251         my $mvr;
1252
1253         if( $rec->id == OILS_PRECAT_RECORD ) {
1254                 $rec = undef;
1255                 $vol = undef;
1256         } else { 
1257                 $mvr = $U->record_to_mvr($rec);
1258                 $rec->marc(''); # drop the bulky marc data
1259         }
1260
1261         return {
1262                 circ => $circ,
1263                 copy => $copy,
1264                 volume => $vol,
1265                 record => $rec,
1266                 mvr => $mvr,
1267         };
1268 }
1269
1270
1271
1272 __PACKAGE__->register_method(
1273         method  => "test_batch_circ_events",
1274         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1275 );
1276
1277 #  method for testing the behavior of a given event definition
1278 sub test_batch_circ_events {
1279     my($self, $conn, $auth, $event_def, $barcode) = @_;
1280
1281     my $e = new_editor(authtoken => $auth);
1282         return $e->event unless $e->checkauth;
1283     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1284
1285     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1286         or return $e->event;
1287
1288     my $circ = $e->search_action_circulation(
1289         {target_copy => $copy->id, checkin_time => undef})->[0]
1290         or return $e->event;
1291         
1292     return undef unless $circ;
1293
1294     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1295 }
1296
1297 __PACKAGE__->register_method(
1298         method  => "fire_circ_events", 
1299         api_name        => "open-ils.circ.fire_circ_trigger_events",
1300     signature => q/
1301         General event def runner for circ objects.  If no event def ID
1302         is provided, the hook will be used to find the best event_def
1303         match based on the context org unit
1304     /
1305 );
1306
1307 sub fire_circ_events {
1308     my($self, $conn, $auth, $org_id, $event_def, $hook, $granularity, $circ_ids, $user_data) = @_;
1309
1310     my $e = new_editor(authtoken => $auth);
1311         return $e->event unless $e->checkauth;
1312     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $org_id);
1313
1314     my $circs = $e->batch_retrieve_action_circulation($circ_ids);
1315     return undef unless @$circs;
1316     return $U->fire_object_event($event_def, $hook, $circs, $org_id, $granularity, $user_data)
1317 }
1318
1319 __PACKAGE__->register_method(
1320         method  => "user_payments_list",
1321         api_name        => "open-ils.circ.user_payments.filtered.batch",
1322     stream => 1,
1323         signature => {
1324         desc => q/Returns a fleshed, date-limited set of all payments a user
1325                 has made.  By default, ordered by payment date.  Optionally
1326                 ordered by other columns in the top-level "mp" object/,
1327         params => [
1328             {desc => 'Authentication token', type => 'string'},
1329             {desc => 'User ID', type => 'number'},
1330             {desc => 'Order by column(s), optional.  Array of "mp" class columns', type => 'array'}
1331         ],
1332         return => {desc => q/List of "mp" objects, fleshed with the billable transaction 
1333             and the related fully-realized payment object (e.g money.cash_payment)/}
1334     }
1335 );
1336
1337 sub user_payments_list {
1338     my($self, $conn, $auth, $user_id, $start_date, $end_date, $order_by) = @_;
1339
1340     my $e = new_editor(authtoken => $auth);
1341     return $e->event unless $e->checkauth;
1342
1343     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1344     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $user->home_ou);
1345
1346     $order_by ||= ['payment_ts'];
1347
1348     # all payments by user, between start_date and end_date
1349     my $payments = $e->json_query({
1350         select => {mp => ['id']}, 
1351         from => {
1352             mp => {
1353                 mbt => {
1354                     fkey => 'xact', field => 'id'}
1355             }
1356         }, 
1357         where => {
1358             '+mbt' => {usr => $user_id}, 
1359             '+mp' => {payment_ts => {between => [$start_date, $end_date]}}
1360         },
1361         order_by => {mp => $order_by}
1362     });
1363
1364     for my $payment_id (@$payments) {
1365         my $payment = $e->retrieve_money_payment([
1366             $payment_id->{id}, 
1367             {   
1368                 flesh => 2,
1369                 flesh_fields => {
1370                     mp => [
1371                         'xact',
1372                         'cash_payment',
1373                         'credit_card_payment',
1374                         'credit_payment',
1375                         'check_payment',
1376                         'work_payment',
1377                         'forgive_payment',
1378                         'goods_payment'
1379                     ],
1380                     mbt => [
1381                         'circulation', 
1382                         'grocery',
1383                         'reservation'
1384                     ]
1385                 }
1386             }
1387         ]);
1388         $conn->respond($payment);
1389     }
1390
1391     return undef;
1392 }
1393
1394
1395 __PACKAGE__->register_method(
1396         method  => "retrieve_circ_chain",
1397         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ",
1398     stream => 1,
1399         signature => {
1400         desc => q/Given a circulation, this returns all circulation objects
1401                 that are part of the same chain of renewals./,
1402         params => [
1403             {desc => 'Authentication token', type => 'string'},
1404             {desc => 'Circ ID', type => 'number'},
1405         ],
1406         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1407     }
1408 );
1409
1410 __PACKAGE__->register_method(
1411         method  => "retrieve_circ_chain",
1412         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ.summary",
1413         signature => {
1414         desc => q/Given a circulation, this returns all circulation objects
1415                 that are part of the same chain of renewals./,
1416         params => [
1417             {desc => 'Authentication token', type => 'string'},
1418             {desc => 'Circ ID', type => 'number'},
1419         ],
1420         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1421     }
1422 );
1423
1424 sub retrieve_circ_chain {
1425     my($self, $conn, $auth, $circ_id) = @_;
1426
1427     my $e = new_editor(authtoken => $auth);
1428     return $e->event unless $e->checkauth;
1429         return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1430
1431     if($self->api_name =~ /summary/) {
1432         my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1433         return undef unless $sum;
1434         my $obj = Fieldmapper::action::circ_chain_summary->new;
1435         $obj->$_($sum->{$_}) for keys %$sum;
1436         return $obj;
1437
1438     } else {
1439
1440         my $chain = $e->json_query({from => ['action.circ_chain', $circ_id]});
1441
1442         for my $circ_info (@$chain) {
1443             my $circ = Fieldmapper::action::circulation->new;
1444             $circ->$_($circ_info->{$_}) for keys %$circ_info;
1445             $conn->respond($circ);
1446         }
1447     }
1448
1449     return undef;
1450 }
1451
1452
1453
1454 # {"select":{"acp":["id"],"circ":[{"aggregate":true,"transform":"count","alias":"count","column":"id"}]},"from":{"acp":{"circ":{"field":"target_copy","fkey":"id","type":"left"},"acn"{"field":"id","fkey":"call_number"}}},"where":{"+acn":{"record":200057}}
1455
1456
1457 1;