]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
b1f30d666adeec6415e4b7930ae92b1d1bf02c49
[working/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         authoritative   => 1,
656         api_name                => 'open-ils.circ.copy_note.retrieve.all',
657         signature       => q/
658                 Returns an array of copy note objects.  
659                 @param args A named hash of parameters including:
660                         authtoken       : Required if viewing non-public notes
661                         itemid          : The id of the item whose notes we want to retrieve
662                         pub                     : True if all the caller wants are public notes
663                 @return An array of note objects
664         /);
665
666 __PACKAGE__->register_method(
667         method          => 'fetch_notes',
668         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
669         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
670
671 __PACKAGE__->register_method(
672         method          => 'fetch_notes',
673         api_name                => 'open-ils.circ.title_note.retrieve.all',
674         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
675
676
677 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
678 sub fetch_notes {
679         my( $self, $connection, $args ) = @_;
680
681         my $id = $$args{itemid};
682         my $authtoken = $$args{authtoken};
683         my( $r, $evt);
684
685         if( $self->api_name =~ /copy/ ) {
686                 if( $$args{pub} ) {
687                         return $U->cstorereq(
688                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
689                                 { owning_copy => $id, pub => 't' } );
690                 } else {
691                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
692                         return $evt if $evt;
693                         return $U->cstorereq(
694                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
695                 }
696
697         } elsif( $self->api_name =~ /call_number/ ) {
698                 if( $$args{pub} ) {
699                         return $U->cstorereq(
700                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
701                                 { call_number => $id, pub => 't' } );
702                 } else {
703                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
704                         return $evt if $evt;
705                         return $U->cstorereq(
706                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
707                 }
708
709         } elsif( $self->api_name =~ /title/ ) {
710                 if( $$args{pub} ) {
711                         return $U->cstorereq(
712                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
713                                 { record => $id, pub => 't' } );
714                 } else {
715                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
716                         return $evt if $evt;
717                         return $U->cstorereq(
718                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
719                 }
720         }
721
722         return undef;
723 }
724
725 __PACKAGE__->register_method(
726         method  => 'has_notes',
727         api_name        => 'open-ils.circ.copy.has_notes');
728 __PACKAGE__->register_method(
729         method  => 'has_notes',
730         api_name        => 'open-ils.circ.call_number.has_notes');
731 __PACKAGE__->register_method(
732         method  => 'has_notes',
733         api_name        => 'open-ils.circ.title.has_notes');
734
735
736 sub has_notes {
737         my( $self, $conn, $authtoken, $id ) = @_;
738         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
739         return $editor->event unless $editor->checkauth;
740
741         my $n = $editor->search_asset_copy_note(
742                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
743
744         $n = $editor->search_asset_call_number_note(
745                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
746
747         $n = $editor->search_biblio_record_note(
748                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
749
750         return scalar @$n;
751 }
752
753
754
755 __PACKAGE__->register_method(
756         method          => 'create_copy_note',
757         api_name                => 'open-ils.circ.copy_note.create',
758         signature       => q/
759                 Creates a new copy note
760                 @param authtoken The login session key
761                 @param note     The note object to create
762                 @return The id of the new note object
763         /);
764
765 sub create_copy_note {
766         my( $self, $connection, $authtoken, $note ) = @_;
767
768         my $e = new_editor(xact=>1, authtoken=>$authtoken);
769         return $e->event unless $e->checkauth;
770         my $copy = $e->retrieve_asset_copy(
771                 [
772                         $note->owning_copy,
773                         {       flesh => 1,
774                                 flesh_fields => { 'acp' => ['call_number'] }
775                         }
776                 ]
777         );
778
779         return $e->event unless 
780                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
781
782         $note->create_date('now');
783         $note->creator($e->requestor->id);
784         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
785         $note->clear_id;
786
787         $e->create_asset_copy_note($note) or return $e->event;
788         $e->commit;
789         return $note->id;
790 }
791
792
793 __PACKAGE__->register_method(
794         method          => 'delete_copy_note',
795         api_name                =>      'open-ils.circ.copy_note.delete',
796         signature       => q/
797                 Deletes an existing copy note
798                 @param authtoken The login session key
799                 @param noteid The id of the note to delete
800                 @return 1 on success - Event otherwise.
801                 /);
802 sub delete_copy_note {
803         my( $self, $conn, $authtoken, $noteid ) = @_;
804
805         my $e = new_editor(xact=>1, authtoken=>$authtoken);
806         return $e->die_event unless $e->checkauth;
807
808         my $note = $e->retrieve_asset_copy_note([
809                 $noteid,
810                 { flesh => 2,
811                         flesh_fields => {
812                                 'acpn' => [ 'owning_copy' ],
813                                 'acp' => [ 'call_number' ],
814                         }
815                 }
816         ]) or return $e->die_event;
817
818         if( $note->creator ne $e->requestor->id ) {
819                 return $e->die_event unless 
820                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
821         }
822
823         $e->delete_asset_copy_note($note) or return $e->die_event;
824         $e->commit;
825         return 1;
826 }
827
828
829 __PACKAGE__->register_method(
830         method => 'age_hold_rules',
831         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
832 );
833
834 sub age_hold_rules {
835         my( $self, $conn ) = @_;
836         return new_editor()->retrieve_all_config_rules_age_hold_protect();
837 }
838
839
840
841 __PACKAGE__->register_method(
842         method => 'copy_details_barcode',
843     authoritative => 1,
844         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
845 sub copy_details_barcode {
846         my( $self, $conn, $auth, $barcode ) = @_;
847     my $e = new_editor();
848     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
849     return $e->event unless $cid;
850         return copy_details( $self, $conn, $auth, $cid );
851 }
852
853
854 __PACKAGE__->register_method(
855         method => 'copy_details',
856         api_name => 'open-ils.circ.copy_details.retrieve');
857
858 sub copy_details {
859         my( $self, $conn, $auth, $copy_id ) = @_;
860         my $e = new_editor(authtoken=>$auth);
861         return $e->event unless $e->checkauth;
862
863         my $flesh = { flesh => 1 };
864
865         my $copy = $e->retrieve_asset_copy(
866                 [
867                         $copy_id,
868                         {
869                                 flesh => 2,
870                                 flesh_fields => {
871                                         acp => ['call_number'],
872                                         acn => ['record']
873                                 }
874                         }
875                 ]) or return $e->event;
876
877
878         # De-flesh the copy for backwards compatibility
879         my $mvr;
880         my $vol = $copy->call_number;
881         if( ref $vol ) {
882                 $copy->call_number($vol->id);
883                 my $record = $vol->record;
884                 if( ref $record ) {
885                         $vol->record($record->id);
886                         $mvr = $U->record_to_mvr($record);
887                 }
888         }
889
890
891         my $hold = $e->search_action_hold_request(
892                 { 
893                         current_copy            => $copy_id, 
894                         capture_time            => { "!=" => undef },
895                         fulfillment_time        => undef,
896                         cancel_time                     => undef,
897                 }
898         )->[0];
899
900         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
901
902         my $transit = $e->search_action_transit_copy(
903                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
904
905         # find the latest circ, open or closed
906         my $circ = $e->search_action_circulation(
907                 [
908                         { target_copy => $copy_id },
909                         { 
910                 flesh => 1,
911                 flesh_fields => {
912                     circ => [
913                         'workstation',
914                         'checkin_workstation', 
915                         'duration_rule', 
916                         'max_fine_rule', 
917                         'recurring_fine_rule'
918                     ]
919                 },
920                 order_by => { circ => 'xact_start desc' }, 
921                 limit => 1 
922             }
923                 ]
924         )->[0];
925
926
927         return {
928                 copy            => $copy,
929                 hold            => $hold,
930                 transit => $transit,
931                 circ            => $circ,
932                 volume  => $vol,
933                 mvr             => $mvr,
934         };
935 }
936
937
938
939
940 __PACKAGE__->register_method(
941         method => 'mark_item',
942         api_name => 'open-ils.circ.mark_item_damaged',
943         signature       => q/
944                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
945                 @param authtoken The login session key
946                 @param copy_id The ID of the copy to mark as damaged
947                 @return 1 on success - Event otherwise.
948                 /
949 );
950 __PACKAGE__->register_method(
951         method => 'mark_item',
952         api_name => 'open-ils.circ.mark_item_missing',
953         signature       => q/
954                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
955                 @param authtoken The login session key
956                 @param copy_id The ID of the copy to mark as missing 
957                 @return 1 on success - Event otherwise.
958                 /
959 );
960 __PACKAGE__->register_method(
961         method => 'mark_item',
962         api_name => 'open-ils.circ.mark_item_bindery',
963         signature       => q/
964                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
965                 @param authtoken The login session key
966                 @param copy_id The ID of the copy to mark as bindery
967                 @return 1 on success - Event otherwise.
968                 /
969 );
970 __PACKAGE__->register_method(
971         method => 'mark_item',
972         api_name => 'open-ils.circ.mark_item_on_order',
973         signature       => q/
974                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
975                 @param authtoken The login session key
976                 @param copy_id The ID of the copy to mark as on order 
977                 @return 1 on success - Event otherwise.
978                 /
979 );
980 __PACKAGE__->register_method(
981         method => 'mark_item',
982         api_name => 'open-ils.circ.mark_item_ill',
983         signature       => q/
984                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
985                 @param authtoken The login session key
986                 @param copy_id The ID of the copy to mark as inter-library loan
987                 @return 1 on success - Event otherwise.
988                 /
989 );
990 __PACKAGE__->register_method(
991         method => 'mark_item',
992         api_name => 'open-ils.circ.mark_item_cataloging',
993         signature       => q/
994                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
995                 @param authtoken The login session key
996                 @param copy_id The ID of the copy to mark as cataloging 
997                 @return 1 on success - Event otherwise.
998                 /
999 );
1000 __PACKAGE__->register_method(
1001         method => 'mark_item',
1002         api_name => 'open-ils.circ.mark_item_reserves',
1003         signature       => q/
1004                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
1005                 @param authtoken The login session key
1006                 @param copy_id The ID of the copy to mark as reserves
1007                 @return 1 on success - Event otherwise.
1008                 /
1009 );
1010 __PACKAGE__->register_method(
1011         method => 'mark_item',
1012         api_name => 'open-ils.circ.mark_item_discard',
1013         signature       => q/
1014                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
1015                 @param authtoken The login session key
1016                 @param copy_id The ID of the copy to mark as discard
1017                 @return 1 on success - Event otherwise.
1018                 /
1019 );
1020
1021 sub mark_item {
1022         my( $self, $conn, $auth, $copy_id, $args ) = @_;
1023         my $e = new_editor(authtoken=>$auth, xact =>1);
1024         return $e->die_event unless $e->checkauth;
1025     $args ||= {};
1026
1027     my $copy = $e->retrieve_asset_copy([
1028         $copy_id,
1029         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
1030             or return $e->die_event;
1031
1032     my $owning_lib = 
1033         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
1034             $copy->circ_lib : $copy->call_number->owning_lib;
1035
1036     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
1037
1038
1039         my $perm = 'MARK_ITEM_MISSING';
1040         my $stat = OILS_COPY_STATUS_MISSING;
1041
1042         if( $self->api_name =~ /damaged/ ) {
1043                 $perm = 'MARK_ITEM_DAMAGED';
1044                 $stat = OILS_COPY_STATUS_DAMAGED;
1045         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
1046         return $evt if $evt;
1047
1048         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1049         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
1050
1051         } elsif ( $self->api_name =~ /bindery/ ) {
1052                 $perm = 'MARK_ITEM_BINDERY';
1053                 $stat = OILS_COPY_STATUS_BINDERY;
1054         } elsif ( $self->api_name =~ /on_order/ ) {
1055                 $perm = 'MARK_ITEM_ON_ORDER';
1056                 $stat = OILS_COPY_STATUS_ON_ORDER;
1057         } elsif ( $self->api_name =~ /ill/ ) {
1058                 $perm = 'MARK_ITEM_ILL';
1059                 $stat = OILS_COPY_STATUS_ILL;
1060         } elsif ( $self->api_name =~ /cataloging/ ) {
1061                 $perm = 'MARK_ITEM_CATALOGING';
1062                 $stat = OILS_COPY_STATUS_CATALOGING;
1063         } elsif ( $self->api_name =~ /reserves/ ) {
1064                 $perm = 'MARK_ITEM_RESERVES';
1065                 $stat = OILS_COPY_STATUS_RESERVES;
1066         } elsif ( $self->api_name =~ /discard/ ) {
1067                 $perm = 'MARK_ITEM_DISCARD';
1068                 $stat = OILS_COPY_STATUS_DISCARD;
1069         }
1070
1071
1072         $copy->status($stat);
1073         $copy->edit_date('now');
1074         $copy->editor($e->requestor->id);
1075
1076         $e->update_asset_copy($copy) or return $e->die_event;
1077
1078         my $holds = $e->search_action_hold_request(
1079                 { 
1080                         current_copy => $copy->id,
1081                         fulfillment_time => undef,
1082                         cancel_time => undef,
1083                 }
1084         );
1085
1086         $e->commit;
1087
1088         $logger->debug("resetting holds that target the marked copy");
1089         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
1090
1091         return 1;
1092 }
1093
1094 sub handle_mark_damaged {
1095     my($e, $copy, $owning_lib, $args) = @_;
1096
1097     my $apply = $args->{apply_fines} || '';
1098     return undef if $apply eq 'noapply';
1099
1100     my $new_amount = $args->{override_amount};
1101     my $new_btype = $args->{override_btype};
1102     my $new_note = $args->{override_note};
1103
1104     # grab the last circulation
1105     my $circ = $e->search_action_circulation([
1106         {   target_copy => $copy->id}, 
1107         {   limit => 1, 
1108             order_by => {circ => "xact_start DESC"},
1109             flesh => 2,
1110             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
1111         }
1112     ])->[0];
1113
1114     return undef unless $circ;
1115
1116     my $charge_price = $U->ou_ancestor_setting_value(
1117         $owning_lib, 'circ.charge_on_damaged', $e);
1118
1119     my $proc_fee = $U->ou_ancestor_setting_value(
1120         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1121
1122     my $void_overdue = $U->ou_ancestor_setting_value(
1123         $owning_lib, 'circ.damaged.void_ovedue', $e) || 0;
1124
1125     return undef unless $charge_price or $proc_fee;
1126
1127     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1128     my $total = $copy_price + $proc_fee;
1129
1130     if($apply) {
1131         
1132         if($new_amount and $new_btype) {
1133
1134             # Allow staff to override the amount to charge for a damaged item
1135             # Consider the case where the item is only partially damaged
1136             # This value is meant to take the place of the item price and
1137             # optional processing fee.
1138
1139             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1140                 $e, $new_amount, $new_btype, 'Damaged Item Override', $circ->id, $new_note);
1141             return $evt if $evt;
1142
1143         } else {
1144
1145             if($charge_price and $copy_price) {
1146                 my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1147                     $e, $copy_price, 7, 'Damaged Item', $circ->id);
1148                 return $evt if $evt;
1149             }
1150
1151             if($proc_fee) {
1152                 my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1153                     $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1154                 return $evt if $evt;
1155             }
1156         }
1157
1158         # the assumption is that you would not void the overdues unless you 
1159         # were also charging for the item and/or applying a processing fee
1160         if($void_overdue) {
1161             my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ);
1162             return $evt if $evt;
1163         }
1164
1165         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1166         return $evt if $evt;
1167
1168         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1169         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1170
1171         return undef;
1172
1173     } else {
1174         return OpenILS::Event->new('DAMAGE_CHARGE', 
1175             payload => {
1176                 circ => $circ,
1177                 charge => $total
1178             }
1179         );
1180     }
1181 }
1182
1183
1184
1185
1186
1187
1188 # ----------------------------------------------------------------------
1189 __PACKAGE__->register_method(
1190         method => 'magic_fetch',
1191         api_name => 'open-ils.agent.fetch'
1192 );
1193
1194 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1195
1196 sub magic_fetch {
1197         my( $self, $conn, $auth, $args ) = @_;
1198         my $e = new_editor( authtoken => $auth );
1199         return $e->event unless $e->checkauth;
1200
1201         my $hint = $$args{hint};
1202         my $id  = $$args{id};
1203
1204         # Is the call allowed to fetch this type of object?
1205         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1206
1207         # Find the class the implements the given hint
1208         my ($class) = grep { 
1209                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1210
1211         $class =~ s/Fieldmapper:://og;
1212         $class =~ s/::/_/og;
1213         my $method = "retrieve_$class";
1214
1215         my $obj = $e->$method($id) or return $e->event;
1216         return $obj;
1217 }
1218 # ----------------------------------------------------------------------
1219
1220
1221 __PACKAGE__->register_method(
1222         method  => "fleshed_circ_retrieve",
1223     authoritative => 1,
1224         api_name        => "open-ils.circ.fleshed.retrieve",);
1225
1226 sub fleshed_circ_retrieve {
1227         my( $self, $client, $id ) = @_;
1228         my $e = new_editor();
1229         my $circ = $e->retrieve_action_circulation(
1230                 [
1231                         $id,
1232                         { 
1233                                 flesh                           => 4,
1234                                 flesh_fields    => { 
1235                                         circ => [ qw/ target_copy / ],
1236                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1237                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1238                                         acn => [ qw/ record / ],
1239                                 }
1240                         }
1241                 ]
1242         ) or return $e->event;
1243         
1244         my $copy = $circ->target_copy;
1245         my $vol = $copy->call_number;
1246         my $rec = $circ->target_copy->call_number->record;
1247
1248         $vol->record($rec->id);
1249         $copy->call_number($vol->id);
1250         $circ->target_copy($copy->id);
1251
1252         my $mvr;
1253
1254         if( $rec->id == OILS_PRECAT_RECORD ) {
1255                 $rec = undef;
1256                 $vol = undef;
1257         } else { 
1258                 $mvr = $U->record_to_mvr($rec);
1259                 $rec->marc(''); # drop the bulky marc data
1260         }
1261
1262         return {
1263                 circ => $circ,
1264                 copy => $copy,
1265                 volume => $vol,
1266                 record => $rec,
1267                 mvr => $mvr,
1268         };
1269 }
1270
1271
1272
1273 __PACKAGE__->register_method(
1274         method  => "test_batch_circ_events",
1275         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1276 );
1277
1278 #  method for testing the behavior of a given event definition
1279 sub test_batch_circ_events {
1280     my($self, $conn, $auth, $event_def, $barcode) = @_;
1281
1282     my $e = new_editor(authtoken => $auth);
1283         return $e->event unless $e->checkauth;
1284     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1285
1286     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1287         or return $e->event;
1288
1289     my $circ = $e->search_action_circulation(
1290         {target_copy => $copy->id, checkin_time => undef})->[0]
1291         or return $e->event;
1292         
1293     return undef unless $circ;
1294
1295     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1296 }
1297
1298
1299 __PACKAGE__->register_method(
1300         method  => "fire_circ_events", 
1301         api_name        => "open-ils.circ.fire_circ_trigger_events",
1302     signature => q/
1303         General event def runner for circ objects.  If no event def ID
1304         is provided, the hook will be used to find the best event_def
1305         match based on the context org unit
1306     /
1307 );
1308
1309 __PACKAGE__->register_method(
1310         method  => "fire_circ_events", 
1311         api_name        => "open-ils.circ.fire_hold_trigger_events",
1312     signature => q/
1313         General event def runner for hold objects.  If no event def ID
1314         is provided, the hook will be used to find the best event_def
1315         match based on the context org unit
1316     /
1317 );
1318
1319 __PACKAGE__->register_method(
1320         method  => "fire_circ_events", 
1321         api_name        => "open-ils.circ.fire_user_trigger_events",
1322     signature => q/
1323         General event def runner for user objects.  If no event def ID
1324         is provided, the hook will be used to find the best event_def
1325         match based on the context org unit
1326     /
1327 );
1328
1329
1330 sub fire_circ_events {
1331     my($self, $conn, $auth, $org_id, $event_def, $hook, $granularity, $target_ids, $user_data) = @_;
1332
1333     my $e = new_editor(authtoken => $auth);
1334         return $e->event unless $e->checkauth;
1335
1336     my $targets;
1337
1338     if($self->api_name =~ /hold/) {
1339         return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1340         $targets = $e->batch_retrieve_action_hold_request($target_ids);
1341     } elsif($self->api_name =~ /user/) {
1342         return $e->event unless $e->allowed('VIEW_USER', $org_id);
1343         $targets = $e->batch_retrieve_actor_user($target_ids);
1344     } else {
1345         return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $org_id);
1346         $targets = $e->batch_retrieve_action_circulation($target_ids);
1347     }
1348
1349     return undef unless @$targets;
1350     return $U->fire_object_event($event_def, $hook, $targets, $org_id, $granularity, $user_data);
1351 }
1352
1353 __PACKAGE__->register_method(
1354         method  => "user_payments_list",
1355         api_name        => "open-ils.circ.user_payments.filtered.batch",
1356     stream => 1,
1357         signature => {
1358         desc => q/Returns a fleshed, date-limited set of all payments a user
1359                 has made.  By default, ordered by payment date.  Optionally
1360                 ordered by other columns in the top-level "mp" object/,
1361         params => [
1362             {desc => 'Authentication token', type => 'string'},
1363             {desc => 'User ID', type => 'number'},
1364             {desc => 'Order by column(s), optional.  Array of "mp" class columns', type => 'array'}
1365         ],
1366         return => {desc => q/List of "mp" objects, fleshed with the billable transaction 
1367             and the related fully-realized payment object (e.g money.cash_payment)/}
1368     }
1369 );
1370
1371 sub user_payments_list {
1372     my($self, $conn, $auth, $user_id, $start_date, $end_date, $order_by) = @_;
1373
1374     my $e = new_editor(authtoken => $auth);
1375     return $e->event unless $e->checkauth;
1376
1377     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1378     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $user->home_ou);
1379
1380     $order_by ||= ['payment_ts'];
1381
1382     # all payments by user, between start_date and end_date
1383     my $payments = $e->json_query({
1384         select => {mp => ['id']}, 
1385         from => {
1386             mp => {
1387                 mbt => {
1388                     fkey => 'xact', field => 'id'}
1389             }
1390         }, 
1391         where => {
1392             '+mbt' => {usr => $user_id}, 
1393             '+mp' => {payment_ts => {between => [$start_date, $end_date]}}
1394         },
1395         order_by => {mp => $order_by}
1396     });
1397
1398     for my $payment_id (@$payments) {
1399         my $payment = $e->retrieve_money_payment([
1400             $payment_id->{id}, 
1401             {   
1402                 flesh => 2,
1403                 flesh_fields => {
1404                     mp => [
1405                         'xact',
1406                         'cash_payment',
1407                         'credit_card_payment',
1408                         'credit_payment',
1409                         'check_payment',
1410                         'work_payment',
1411                         'forgive_payment',
1412                         'goods_payment'
1413                     ],
1414                     mbt => [
1415                         'circulation', 
1416                         'grocery',
1417                         'reservation'
1418                     ]
1419                 }
1420             }
1421         ]);
1422         $conn->respond($payment);
1423     }
1424
1425     return undef;
1426 }
1427
1428
1429 __PACKAGE__->register_method(
1430         method  => "retrieve_circ_chain",
1431         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ",
1432     stream => 1,
1433         signature => {
1434         desc => q/Given a circulation, this returns all circulation objects
1435                 that are part of the same chain of renewals./,
1436         params => [
1437             {desc => 'Authentication token', type => 'string'},
1438             {desc => 'Circ ID', type => 'number'},
1439         ],
1440         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1441     }
1442 );
1443
1444 __PACKAGE__->register_method(
1445         method  => "retrieve_circ_chain",
1446         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ.summary",
1447         signature => {
1448         desc => q/Given a circulation, this returns all circulation objects
1449                 that are part of the same chain of renewals./,
1450         params => [
1451             {desc => 'Authentication token', type => 'string'},
1452             {desc => 'Circ ID', type => 'number'},
1453         ],
1454         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1455     }
1456 );
1457
1458 sub retrieve_circ_chain {
1459     my($self, $conn, $auth, $circ_id) = @_;
1460
1461     my $e = new_editor(authtoken => $auth);
1462     return $e->event unless $e->checkauth;
1463         return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1464
1465     if($self->api_name =~ /summary/) {
1466         my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1467         return undef unless $sum;
1468         my $obj = Fieldmapper::action::circ_chain_summary->new;
1469         $obj->$_($sum->{$_}) for keys %$sum;
1470         return $obj;
1471
1472     } else {
1473
1474         my $chain = $e->json_query({from => ['action.circ_chain', $circ_id]});
1475
1476         for my $circ_info (@$chain) {
1477             my $circ = Fieldmapper::action::circulation->new;
1478             $circ->$_($circ_info->{$_}) for keys %$circ_info;
1479             $conn->respond($circ);
1480         }
1481     }
1482
1483     return undef;
1484 }
1485
1486
1487
1488 # {"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}}
1489
1490
1491 1;