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