]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
middle layer methods for getting at a 'preceeding' circ renewal chain given a circ id
[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         $backdate = cleanse_ISO8601($backdate);
371
372         my $original_date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($circ->due_date));
373         my $new_date = DateTime::Format::ISO8601->new->parse_datetime($backdate);
374         $backdate = $new_date->ymd . 'T' . $original_date->strftime('%T%z');
375
376         # make it look like the circ stopped at the cliams returned time
377         $circ->stop_fines_time($backdate);
378         my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
379         return $evt if $evt;
380     }
381
382     $e->update_action_circulation($circ) or return $e->die_event;
383
384     # see if there is a configured post-claims-return copy status
385     if(my $stat = $U->ou_ancestor_setting_value($circ->circ_lib, 'circ.claim_return.copy_status')) {
386             $copy->status($stat);
387             $copy->edit_date('now');
388             $copy->editor($e->requestor->id);
389             $e->update_asset_copy($copy) or return $e->die_event;
390     }
391
392     $e->commit;
393     return 1;
394 }
395
396
397 __PACKAGE__->register_method(
398         method  => "post_checkin_backdate_circ",
399         api_name        => "open-ils.circ.post_checkin_backdate",
400         signature => {
401         desc => q/Back-date an already checked in circulation/,
402         params => [
403             {desc => 'Authentication token', type => 'string'},
404             {desc => 'Circ ID', type => 'number'},
405             {desc => 'ISO8601 backdate', type => 'string'},
406         ],
407         return => {desc => q/1 on success, failure event on error/}
408     }
409 );
410
411 __PACKAGE__->register_method(
412         method  => "post_checkin_backdate_circ",
413         api_name        => "open-ils.circ.post_checkin_backdate.batch",
414     stream => 1,
415         signature => {
416         desc => q/@see open-ils.circ.post_checkin_backdate.  Batch mode/,
417         params => [
418             {desc => 'Authentication token', type => 'string'},
419             {desc => 'List of Circ ID', type => 'array'},
420             {desc => 'ISO8601 backdate', type => 'string'},
421         ],
422         return => {desc => q/Set of: 1 on success, failure event on error/}
423     }
424 );
425
426
427 sub post_checkin_backdate_circ {
428     my( $self, $conn, $auth, $circ_id, $backdate ) = @_;
429     my $e = new_editor(authtoken=>$auth);
430     return $e->die_event unless $e->checkauth;
431     if($self->api_name =~ /batch/) {
432         foreach my $c (@$circ_id) {
433             $conn->respond(post_checkin_backdate_circ_impl($e, $c, $backdate));
434         }
435     } else {
436         $conn->respond_complete(post_checkin_backdate_circ_impl($e, $circ_id, $backdate));
437     }
438
439     $e->disconnect;
440     return undef;
441 }
442
443
444 sub post_checkin_backdate_circ_impl {
445     my($e, $circ_id, $backdate) = @_;
446
447     $e->xact_begin;
448
449     my $circ = $e->retrieve_action_circulation($circ_id)
450         or return $e->die_event;
451
452     # anyone with checkin perms can backdate (more restrictive?)
453     return $e->die_event unless $e->allowed('COPY_CHECKIN', $circ->circ_lib);
454
455     # don't allow back-dating an open circulation
456     return OpenILS::Event->new('BAD_PARAMS') unless 
457         $backdate and $circ->checkin_time;
458
459     # update the checkin and stop_fines times to reflect the new backdate
460     $circ->stop_fines_time(cleanse_ISO8601($backdate));
461     $circ->checkin_time(cleanse_ISO8601($backdate));
462     $e->update_action_circulation($circ) or return $e->die_event;
463
464     # now void the overdues "erased" by the back-dating
465     my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
466     return $evt if $evt;
467
468     # If the circ was closed before and the balance owned !=0, re-open the transaction
469     $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
470     return $evt if $evt;
471
472     $e->xact_commit;
473     return 1;
474 }
475
476
477
478 __PACKAGE__->register_method (
479         method          => 'set_circ_due_date',
480         api_name                => 'open-ils.circ.circulation.due_date.update',
481         signature       => q/
482                 Updates the due_date on the given circ
483                 @param authtoken
484                 @param circid The id of the circ to update
485                 @param date The timestamp of the new due date
486         /
487 );
488
489 sub set_circ_due_date {
490         my( $self, $conn, $auth, $circ_id, $date ) = @_;
491
492     my $e = new_editor(xact=>1, authtoken=>$auth);
493     return $e->die_event unless $e->checkauth;
494     my $circ = $e->retrieve_action_circulation($circ_id)
495         or return $e->die_event;
496
497     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
498         $date = cleanse_ISO8601($date);
499
500     if (!(interval_to_seconds($circ->duration) % 86400)) { # duration is divisible by days
501         my $original_date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($circ->due_date));
502         my $new_date = DateTime::Format::ISO8601->new->parse_datetime($date);
503         $date = $new_date->ymd . 'T' . $original_date->strftime('%T%z');
504     }
505
506         $circ->due_date($date);
507     $e->update_action_circulation($circ) or return $e->die_event;
508     $e->commit;
509
510     return $circ->id;
511 }
512
513
514 __PACKAGE__->register_method(
515         method          => "create_in_house_use",
516         api_name                => 'open-ils.circ.in_house_use.create',
517         signature       =>      q/
518                 Creates an in-house use action.
519                 @param $authtoken The login session key
520                 @param params A hash of params including
521                         'location' The org unit id where the in-house use occurs
522                         'copyid' The copy in question
523                         'count' The number of in-house uses to apply to this copy
524                 @return An array of id's representing the id's of the newly created
525                 in-house use objects or an event on an error
526         /);
527
528 __PACKAGE__->register_method(
529         method          => "create_in_house_use",
530         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
531 );
532
533
534 sub create_in_house_use {
535         my( $self, $client, $auth, $params ) = @_;
536
537         my( $evt, $copy );
538         my $org                 = $params->{location};
539         my $copyid              = $params->{copyid};
540         my $count               = $params->{count} || 1;
541         my $nc_type             = $params->{non_cat_type};
542         my $use_time    = $params->{use_time} || 'now';
543
544         my $e = new_editor(xact=>1,authtoken=>$auth);
545         return $e->event unless $e->checkauth;
546         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
547
548         my $non_cat = 1 if $self->api_name =~ /non_cat/;
549
550         unless( $non_cat ) {
551                 if( $copyid ) {
552                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
553                 } else {
554                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
555                                 or return $e->event;
556                         $copyid = $copy->id;
557                 }
558         }
559
560         if( $use_time ne 'now' ) {
561                 $use_time = cleanse_ISO8601($use_time);
562                 $logger->debug("in_house_use setting use time to $use_time");
563         }
564
565         my @ids;
566         for(1..$count) {
567
568                 my $ihu;
569                 my $method;
570                 my $cmeth;
571
572                 if($non_cat) {
573                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
574                         $ihu->item_type($nc_type);
575                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
576                         $cmeth = "create_action_non_cat_in_house_use";
577
578                 } else {
579                         $ihu = Fieldmapper::action::in_house_use->new;
580                         $ihu->item($copyid);
581                         $method = 'open-ils.storage.direct.action.in_house_use.create';
582                         $cmeth = "create_action_in_house_use";
583                 }
584
585                 $ihu->staff($e->requestor->id);
586                 $ihu->org_unit($org);
587                 $ihu->use_time($use_time);
588
589                 $ihu = $e->$cmeth($ihu) or return $e->event;
590                 push( @ids, $ihu->id );
591         }
592
593         $e->commit;
594         return \@ids;
595 }
596
597
598
599
600
601 __PACKAGE__->register_method(
602         method  => "view_circs",
603         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
604         notes           => q/
605                 Retrieves the last X circs for a given copy
606                 @param authtoken The login session key
607                 @param copyid The copy to check
608                 @param count How far to go back in the item history
609                 @return An array of circ ids
610         /);
611
612 # ----------------------------------------------------------------------
613 # Returns $count most recent circs.  If count exceeds the configured 
614 # max, use the configured max instead
615 # ----------------------------------------------------------------------
616 sub view_circs {
617         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
618
619     my $e = new_editor(authtoken => $authtoken);
620     return $e->event unless $e->checkauth;
621     
622     my $copy = $e->retrieve_asset_copy([
623         $copyid,
624         {   flesh => 1,
625             flesh_fields => {acp => ['call_number']}
626         }
627     ]) or return $e->event;
628
629     return $e->event unless $e->allowed(
630         'VIEW_COPY_CHECKOUT_HISTORY', 
631         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
632             $copy->circ_lib : $copy->call_number->owning_lib);
633         
634     my $max_history = $U->ou_ancestor_setting_value(
635         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
636
637     if(defined $max_history) {
638         $count = $max_history unless defined $count and $count < $max_history;
639     } else {
640         $count = 4 unless defined $count;
641     }
642
643     return $e->search_action_circulation([
644         {target_copy => $copyid}, 
645         {limit => $count, order_by => { circ => "xact_start DESC" }} 
646     ]);
647 }
648
649
650 __PACKAGE__->register_method(
651         method  => "circ_count",
652         api_name        => "open-ils.circ.circulation.count",
653         notes           => q/
654                 Returns the number of times the item has circulated
655                 @param copyid The copy to check
656         /);
657
658 sub circ_count {
659         my( $self, $client, $copyid, $range ) = @_; 
660         my $e = OpenILS::Utils::Editor->new;
661         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
662 }
663
664
665
666 __PACKAGE__->register_method(
667         method          => 'fetch_notes',
668         authoritative   => 1,
669         api_name                => 'open-ils.circ.copy_note.retrieve.all',
670         signature       => q/
671                 Returns an array of copy note objects.  
672                 @param args A named hash of parameters including:
673                         authtoken       : Required if viewing non-public notes
674                         itemid          : The id of the item whose notes we want to retrieve
675                         pub                     : True if all the caller wants are public notes
676                 @return An array of note objects
677         /);
678
679 __PACKAGE__->register_method(
680         method          => 'fetch_notes',
681         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
682         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
683
684 __PACKAGE__->register_method(
685         method          => 'fetch_notes',
686         api_name                => 'open-ils.circ.title_note.retrieve.all',
687         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
688
689
690 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
691 sub fetch_notes {
692         my( $self, $connection, $args ) = @_;
693
694         my $id = $$args{itemid};
695         my $authtoken = $$args{authtoken};
696         my( $r, $evt);
697
698         if( $self->api_name =~ /copy/ ) {
699                 if( $$args{pub} ) {
700                         return $U->cstorereq(
701                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
702                                 { owning_copy => $id, pub => 't' } );
703                 } else {
704                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
705                         return $evt if $evt;
706                         return $U->cstorereq(
707                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
708                 }
709
710         } elsif( $self->api_name =~ /call_number/ ) {
711                 if( $$args{pub} ) {
712                         return $U->cstorereq(
713                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
714                                 { call_number => $id, pub => 't' } );
715                 } else {
716                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
717                         return $evt if $evt;
718                         return $U->cstorereq(
719                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
720                 }
721
722         } elsif( $self->api_name =~ /title/ ) {
723                 if( $$args{pub} ) {
724                         return $U->cstorereq(
725                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
726                                 { record => $id, pub => 't' } );
727                 } else {
728                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
729                         return $evt if $evt;
730                         return $U->cstorereq(
731                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
732                 }
733         }
734
735         return undef;
736 }
737
738 __PACKAGE__->register_method(
739         method  => 'has_notes',
740         api_name        => 'open-ils.circ.copy.has_notes');
741 __PACKAGE__->register_method(
742         method  => 'has_notes',
743         api_name        => 'open-ils.circ.call_number.has_notes');
744 __PACKAGE__->register_method(
745         method  => 'has_notes',
746         api_name        => 'open-ils.circ.title.has_notes');
747
748
749 sub has_notes {
750         my( $self, $conn, $authtoken, $id ) = @_;
751         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
752         return $editor->event unless $editor->checkauth;
753
754         my $n = $editor->search_asset_copy_note(
755                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
756
757         $n = $editor->search_asset_call_number_note(
758                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
759
760         $n = $editor->search_biblio_record_note(
761                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
762
763         return scalar @$n;
764 }
765
766
767
768 __PACKAGE__->register_method(
769         method          => 'create_copy_note',
770         api_name                => 'open-ils.circ.copy_note.create',
771         signature       => q/
772                 Creates a new copy note
773                 @param authtoken The login session key
774                 @param note     The note object to create
775                 @return The id of the new note object
776         /);
777
778 sub create_copy_note {
779         my( $self, $connection, $authtoken, $note ) = @_;
780
781         my $e = new_editor(xact=>1, authtoken=>$authtoken);
782         return $e->event unless $e->checkauth;
783         my $copy = $e->retrieve_asset_copy(
784                 [
785                         $note->owning_copy,
786                         {       flesh => 1,
787                                 flesh_fields => { 'acp' => ['call_number'] }
788                         }
789                 ]
790         );
791
792         return $e->event unless 
793                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
794
795         $note->create_date('now');
796         $note->creator($e->requestor->id);
797         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
798         $note->clear_id;
799
800         $e->create_asset_copy_note($note) or return $e->event;
801         $e->commit;
802         return $note->id;
803 }
804
805
806 __PACKAGE__->register_method(
807         method          => 'delete_copy_note',
808         api_name                =>      'open-ils.circ.copy_note.delete',
809         signature       => q/
810                 Deletes an existing copy note
811                 @param authtoken The login session key
812                 @param noteid The id of the note to delete
813                 @return 1 on success - Event otherwise.
814                 /);
815 sub delete_copy_note {
816         my( $self, $conn, $authtoken, $noteid ) = @_;
817
818         my $e = new_editor(xact=>1, authtoken=>$authtoken);
819         return $e->die_event unless $e->checkauth;
820
821         my $note = $e->retrieve_asset_copy_note([
822                 $noteid,
823                 { flesh => 2,
824                         flesh_fields => {
825                                 'acpn' => [ 'owning_copy' ],
826                                 'acp' => [ 'call_number' ],
827                         }
828                 }
829         ]) or return $e->die_event;
830
831         if( $note->creator ne $e->requestor->id ) {
832                 return $e->die_event unless 
833                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
834         }
835
836         $e->delete_asset_copy_note($note) or return $e->die_event;
837         $e->commit;
838         return 1;
839 }
840
841
842 __PACKAGE__->register_method(
843         method => 'age_hold_rules',
844         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
845 );
846
847 sub age_hold_rules {
848         my( $self, $conn ) = @_;
849         return new_editor()->retrieve_all_config_rules_age_hold_protect();
850 }
851
852
853
854 __PACKAGE__->register_method(
855         method => 'copy_details_barcode',
856     authoritative => 1,
857         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
858 sub copy_details_barcode {
859         my( $self, $conn, $auth, $barcode ) = @_;
860     my $e = new_editor();
861     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
862     return $e->event unless $cid;
863         return copy_details( $self, $conn, $auth, $cid );
864 }
865
866
867 __PACKAGE__->register_method(
868         method => 'copy_details',
869         api_name => 'open-ils.circ.copy_details.retrieve');
870
871 sub copy_details {
872         my( $self, $conn, $auth, $copy_id ) = @_;
873         my $e = new_editor(authtoken=>$auth);
874         return $e->event unless $e->checkauth;
875
876         my $flesh = { flesh => 1 };
877
878         my $copy = $e->retrieve_asset_copy(
879                 [
880                         $copy_id,
881                         {
882                                 flesh => 2,
883                                 flesh_fields => {
884                                         acp => ['call_number'],
885                                         acn => ['record']
886                                 }
887                         }
888                 ]) or return $e->event;
889
890
891         # De-flesh the copy for backwards compatibility
892         my $mvr;
893         my $vol = $copy->call_number;
894         if( ref $vol ) {
895                 $copy->call_number($vol->id);
896                 my $record = $vol->record;
897                 if( ref $record ) {
898                         $vol->record($record->id);
899                         $mvr = $U->record_to_mvr($record);
900                 }
901         }
902
903
904         my $hold = $e->search_action_hold_request(
905                 { 
906                         current_copy            => $copy_id, 
907                         capture_time            => { "!=" => undef },
908                         fulfillment_time        => undef,
909                         cancel_time                     => undef,
910                 }
911         )->[0];
912
913         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
914
915         my $transit = $e->search_action_transit_copy(
916                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
917
918         # find the latest circ, open or closed
919         my $circ = $e->search_action_circulation(
920                 [
921                         { target_copy => $copy_id },
922                         { 
923                 flesh => 1,
924                 flesh_fields => {
925                     circ => [
926                         'workstation',
927                         'checkin_workstation', 
928                         'duration_rule', 
929                         'max_fine_rule', 
930                         'recurring_fine_rule'
931                     ]
932                 },
933                 order_by => { circ => 'xact_start desc' }, 
934                 limit => 1 
935             }
936                 ]
937         )->[0];
938
939
940         return {
941                 copy            => $copy,
942                 hold            => $hold,
943                 transit => $transit,
944                 circ            => $circ,
945                 volume  => $vol,
946                 mvr             => $mvr,
947         };
948 }
949
950
951
952
953 __PACKAGE__->register_method(
954         method => 'mark_item',
955         api_name => 'open-ils.circ.mark_item_damaged',
956         signature       => q/
957                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
958                 @param authtoken The login session key
959                 @param copy_id The ID of the copy to mark as damaged
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_missing',
966         signature       => q/
967                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
968                 @param authtoken The login session key
969                 @param copy_id The ID of the copy to mark as missing 
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_bindery',
976         signature       => q/
977                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
978                 @param authtoken The login session key
979                 @param copy_id The ID of the copy to mark as bindery
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_on_order',
986         signature       => q/
987                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
988                 @param authtoken The login session key
989                 @param copy_id The ID of the copy to mark as on order 
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_ill',
996         signature       => q/
997                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
998                 @param authtoken The login session key
999                 @param copy_id The ID of the copy to mark as inter-library loan
1000                 @return 1 on success - Event otherwise.
1001                 /
1002 );
1003 __PACKAGE__->register_method(
1004         method => 'mark_item',
1005         api_name => 'open-ils.circ.mark_item_cataloging',
1006         signature       => q/
1007                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
1008                 @param authtoken The login session key
1009                 @param copy_id The ID of the copy to mark as cataloging 
1010                 @return 1 on success - Event otherwise.
1011                 /
1012 );
1013 __PACKAGE__->register_method(
1014         method => 'mark_item',
1015         api_name => 'open-ils.circ.mark_item_reserves',
1016         signature       => q/
1017                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
1018                 @param authtoken The login session key
1019                 @param copy_id The ID of the copy to mark as reserves
1020                 @return 1 on success - Event otherwise.
1021                 /
1022 );
1023 __PACKAGE__->register_method(
1024         method => 'mark_item',
1025         api_name => 'open-ils.circ.mark_item_discard',
1026         signature       => q/
1027                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
1028                 @param authtoken The login session key
1029                 @param copy_id The ID of the copy to mark as discard
1030                 @return 1 on success - Event otherwise.
1031                 /
1032 );
1033
1034 sub mark_item {
1035         my( $self, $conn, $auth, $copy_id, $args ) = @_;
1036         my $e = new_editor(authtoken=>$auth, xact =>1);
1037         return $e->die_event unless $e->checkauth;
1038     $args ||= {};
1039
1040     my $copy = $e->retrieve_asset_copy([
1041         $copy_id,
1042         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
1043             or return $e->die_event;
1044
1045     my $owning_lib = 
1046         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
1047             $copy->circ_lib : $copy->call_number->owning_lib;
1048
1049     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
1050
1051
1052         my $perm = 'MARK_ITEM_MISSING';
1053         my $stat = OILS_COPY_STATUS_MISSING;
1054
1055         if( $self->api_name =~ /damaged/ ) {
1056                 $perm = 'MARK_ITEM_DAMAGED';
1057                 $stat = OILS_COPY_STATUS_DAMAGED;
1058         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
1059         return $evt if $evt;
1060
1061         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1062         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
1063
1064         } elsif ( $self->api_name =~ /bindery/ ) {
1065                 $perm = 'MARK_ITEM_BINDERY';
1066                 $stat = OILS_COPY_STATUS_BINDERY;
1067         } elsif ( $self->api_name =~ /on_order/ ) {
1068                 $perm = 'MARK_ITEM_ON_ORDER';
1069                 $stat = OILS_COPY_STATUS_ON_ORDER;
1070         } elsif ( $self->api_name =~ /ill/ ) {
1071                 $perm = 'MARK_ITEM_ILL';
1072                 $stat = OILS_COPY_STATUS_ILL;
1073         } elsif ( $self->api_name =~ /cataloging/ ) {
1074                 $perm = 'MARK_ITEM_CATALOGING';
1075                 $stat = OILS_COPY_STATUS_CATALOGING;
1076         } elsif ( $self->api_name =~ /reserves/ ) {
1077                 $perm = 'MARK_ITEM_RESERVES';
1078                 $stat = OILS_COPY_STATUS_RESERVES;
1079         } elsif ( $self->api_name =~ /discard/ ) {
1080                 $perm = 'MARK_ITEM_DISCARD';
1081                 $stat = OILS_COPY_STATUS_DISCARD;
1082         }
1083
1084
1085         $copy->status($stat);
1086         $copy->edit_date('now');
1087         $copy->editor($e->requestor->id);
1088
1089         $e->update_asset_copy($copy) or return $e->die_event;
1090
1091         my $holds = $e->search_action_hold_request(
1092                 { 
1093                         current_copy => $copy->id,
1094                         fulfillment_time => undef,
1095                         cancel_time => undef,
1096                 }
1097         );
1098
1099         $e->commit;
1100
1101         $logger->debug("resetting holds that target the marked copy");
1102         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
1103
1104         return 1;
1105 }
1106
1107 sub handle_mark_damaged {
1108     my($e, $copy, $owning_lib, $args) = @_;
1109
1110     my $apply = $args->{apply_fines} || '';
1111     return undef if $apply eq 'noapply';
1112
1113     my $new_amount = $args->{override_amount};
1114     my $new_btype = $args->{override_btype};
1115     my $new_note = $args->{override_note};
1116
1117     # grab the last circulation
1118     my $circ = $e->search_action_circulation([
1119         {   target_copy => $copy->id}, 
1120         {   limit => 1, 
1121             order_by => {circ => "xact_start DESC"},
1122             flesh => 2,
1123             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
1124         }
1125     ])->[0];
1126
1127     return undef unless $circ;
1128
1129     my $charge_price = $U->ou_ancestor_setting_value(
1130         $owning_lib, 'circ.charge_on_damaged', $e);
1131
1132     my $proc_fee = $U->ou_ancestor_setting_value(
1133         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1134
1135     my $void_overdue = $U->ou_ancestor_setting_value(
1136         $owning_lib, 'circ.damaged.void_ovedue', $e) || 0;
1137
1138     return undef unless $charge_price or $proc_fee;
1139
1140     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1141     my $total = $copy_price + $proc_fee;
1142
1143     if($apply) {
1144         
1145         if($new_amount and $new_btype) {
1146
1147             # Allow staff to override the amount to charge for a damaged item
1148             # Consider the case where the item is only partially damaged
1149             # This value is meant to take the place of the item price and
1150             # optional processing fee.
1151
1152             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1153                 $e, $new_amount, $new_btype, 'Damaged Item Override', $circ->id, $new_note);
1154             return $evt if $evt;
1155
1156         } else {
1157
1158             if($charge_price and $copy_price) {
1159                 my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1160                     $e, $copy_price, 7, 'Damaged Item', $circ->id);
1161                 return $evt if $evt;
1162             }
1163
1164             if($proc_fee) {
1165                 my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1166                     $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1167                 return $evt if $evt;
1168             }
1169         }
1170
1171         # the assumption is that you would not void the overdues unless you 
1172         # were also charging for the item and/or applying a processing fee
1173         if($void_overdue) {
1174             my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ);
1175             return $evt if $evt;
1176         }
1177
1178         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1179         return $evt if $evt;
1180
1181         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1182         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1183
1184         return undef;
1185
1186     } else {
1187         return OpenILS::Event->new('DAMAGE_CHARGE', 
1188             payload => {
1189                 circ => $circ,
1190                 charge => $total
1191             }
1192         );
1193     }
1194 }
1195
1196
1197
1198
1199
1200
1201 # ----------------------------------------------------------------------
1202 __PACKAGE__->register_method(
1203         method => 'magic_fetch',
1204         api_name => 'open-ils.agent.fetch'
1205 );
1206
1207 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1208
1209 sub magic_fetch {
1210         my( $self, $conn, $auth, $args ) = @_;
1211         my $e = new_editor( authtoken => $auth );
1212         return $e->event unless $e->checkauth;
1213
1214         my $hint = $$args{hint};
1215         my $id  = $$args{id};
1216
1217         # Is the call allowed to fetch this type of object?
1218         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1219
1220         # Find the class the implements the given hint
1221         my ($class) = grep { 
1222                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1223
1224         $class =~ s/Fieldmapper:://og;
1225         $class =~ s/::/_/og;
1226         my $method = "retrieve_$class";
1227
1228         my $obj = $e->$method($id) or return $e->event;
1229         return $obj;
1230 }
1231 # ----------------------------------------------------------------------
1232
1233
1234 __PACKAGE__->register_method(
1235         method  => "fleshed_circ_retrieve",
1236     authoritative => 1,
1237         api_name        => "open-ils.circ.fleshed.retrieve",);
1238
1239 sub fleshed_circ_retrieve {
1240         my( $self, $client, $id ) = @_;
1241         my $e = new_editor();
1242         my $circ = $e->retrieve_action_circulation(
1243                 [
1244                         $id,
1245                         { 
1246                                 flesh                           => 4,
1247                                 flesh_fields    => { 
1248                                         circ => [ qw/ target_copy / ],
1249                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1250                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1251                                         acn => [ qw/ record / ],
1252                                 }
1253                         }
1254                 ]
1255         ) or return $e->event;
1256         
1257         my $copy = $circ->target_copy;
1258         my $vol = $copy->call_number;
1259         my $rec = $circ->target_copy->call_number->record;
1260
1261         $vol->record($rec->id);
1262         $copy->call_number($vol->id);
1263         $circ->target_copy($copy->id);
1264
1265         my $mvr;
1266
1267         if( $rec->id == OILS_PRECAT_RECORD ) {
1268                 $rec = undef;
1269                 $vol = undef;
1270         } else { 
1271                 $mvr = $U->record_to_mvr($rec);
1272                 $rec->marc(''); # drop the bulky marc data
1273         }
1274
1275         return {
1276                 circ => $circ,
1277                 copy => $copy,
1278                 volume => $vol,
1279                 record => $rec,
1280                 mvr => $mvr,
1281         };
1282 }
1283
1284
1285
1286 __PACKAGE__->register_method(
1287         method  => "test_batch_circ_events",
1288         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1289 );
1290
1291 #  method for testing the behavior of a given event definition
1292 sub test_batch_circ_events {
1293     my($self, $conn, $auth, $event_def, $barcode) = @_;
1294
1295     my $e = new_editor(authtoken => $auth);
1296         return $e->event unless $e->checkauth;
1297     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1298
1299     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1300         or return $e->event;
1301
1302     my $circ = $e->search_action_circulation(
1303         {target_copy => $copy->id, checkin_time => undef})->[0]
1304         or return $e->event;
1305         
1306     return undef unless $circ;
1307
1308     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1309 }
1310
1311
1312 __PACKAGE__->register_method(
1313         method  => "fire_circ_events", 
1314         api_name        => "open-ils.circ.fire_circ_trigger_events",
1315     signature => q/
1316         General event def runner for circ objects.  If no event def ID
1317         is provided, the hook will be used to find the best event_def
1318         match based on the context org unit
1319     /
1320 );
1321
1322 __PACKAGE__->register_method(
1323         method  => "fire_circ_events", 
1324         api_name        => "open-ils.circ.fire_hold_trigger_events",
1325     signature => q/
1326         General event def runner for hold objects.  If no event def ID
1327         is provided, the hook will be used to find the best event_def
1328         match based on the context org unit
1329     /
1330 );
1331
1332 __PACKAGE__->register_method(
1333         method  => "fire_circ_events", 
1334         api_name        => "open-ils.circ.fire_user_trigger_events",
1335     signature => q/
1336         General event def runner for user objects.  If no event def ID
1337         is provided, the hook will be used to find the best event_def
1338         match based on the context org unit
1339     /
1340 );
1341
1342
1343 sub fire_circ_events {
1344     my($self, $conn, $auth, $org_id, $event_def, $hook, $granularity, $target_ids, $user_data) = @_;
1345
1346     my $e = new_editor(authtoken => $auth);
1347         return $e->event unless $e->checkauth;
1348
1349     my $targets;
1350
1351     if($self->api_name =~ /hold/) {
1352         return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1353         $targets = $e->batch_retrieve_action_hold_request($target_ids);
1354     } elsif($self->api_name =~ /user/) {
1355         return $e->event unless $e->allowed('VIEW_USER', $org_id);
1356         $targets = $e->batch_retrieve_actor_user($target_ids);
1357     } else {
1358         return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $org_id);
1359         $targets = $e->batch_retrieve_action_circulation($target_ids);
1360     }
1361
1362     return undef unless @$targets;
1363     return $U->fire_object_event($event_def, $hook, $targets, $org_id, $granularity, $user_data);
1364 }
1365
1366 __PACKAGE__->register_method(
1367         method  => "user_payments_list",
1368         api_name        => "open-ils.circ.user_payments.filtered.batch",
1369     stream => 1,
1370         signature => {
1371         desc => q/Returns a fleshed, date-limited set of all payments a user
1372                 has made.  By default, ordered by payment date.  Optionally
1373                 ordered by other columns in the top-level "mp" object/,
1374         params => [
1375             {desc => 'Authentication token', type => 'string'},
1376             {desc => 'User ID', type => 'number'},
1377             {desc => 'Order by column(s), optional.  Array of "mp" class columns', type => 'array'}
1378         ],
1379         return => {desc => q/List of "mp" objects, fleshed with the billable transaction 
1380             and the related fully-realized payment object (e.g money.cash_payment)/}
1381     }
1382 );
1383
1384 sub user_payments_list {
1385     my($self, $conn, $auth, $user_id, $start_date, $end_date, $order_by) = @_;
1386
1387     my $e = new_editor(authtoken => $auth);
1388     return $e->event unless $e->checkauth;
1389
1390     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1391     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $user->home_ou);
1392
1393     $order_by ||= ['payment_ts'];
1394
1395     # all payments by user, between start_date and end_date
1396     my $payments = $e->json_query({
1397         select => {mp => ['id']}, 
1398         from => {
1399             mp => {
1400                 mbt => {
1401                     fkey => 'xact', field => 'id'}
1402             }
1403         }, 
1404         where => {
1405             '+mbt' => {usr => $user_id}, 
1406             '+mp' => {payment_ts => {between => [$start_date, $end_date]}}
1407         },
1408         order_by => {mp => $order_by}
1409     });
1410
1411     for my $payment_id (@$payments) {
1412         my $payment = $e->retrieve_money_payment([
1413             $payment_id->{id}, 
1414             {   
1415                 flesh => 2,
1416                 flesh_fields => {
1417                     mp => [
1418                         'xact',
1419                         'cash_payment',
1420                         'credit_card_payment',
1421                         'credit_payment',
1422                         'check_payment',
1423                         'work_payment',
1424                         'forgive_payment',
1425                         'goods_payment'
1426                     ],
1427                     mbt => [
1428                         'circulation', 
1429                         'grocery',
1430                         'reservation'
1431                     ]
1432                 }
1433             }
1434         ]);
1435         $conn->respond($payment);
1436     }
1437
1438     return undef;
1439 }
1440
1441
1442 __PACKAGE__->register_method(
1443         method  => "retrieve_circ_chain",
1444         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ",
1445     stream => 1,
1446         signature => {
1447         desc => q/Given a circulation, this returns all circulation objects
1448                 that are part of the same chain of renewals./,
1449         params => [
1450             {desc => 'Authentication token', type => 'string'},
1451             {desc => 'Circ ID', type => 'number'},
1452         ],
1453         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1454     }
1455 );
1456
1457 __PACKAGE__->register_method(
1458         method  => "retrieve_circ_chain",
1459         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ.summary",
1460         signature => {
1461         desc => q/Given a circulation, this returns a summary of the circulation objects
1462                 that are part of the same chain of renewals./,
1463         params => [
1464             {desc => 'Authentication token', type => 'string'},
1465             {desc => 'Circ ID', type => 'number'},
1466         ],
1467         return => {desc => q/Circulation Chain Summary/}
1468     }
1469 );
1470
1471 sub retrieve_circ_chain {
1472     my($self, $conn, $auth, $circ_id) = @_;
1473
1474     my $e = new_editor(authtoken => $auth);
1475     return $e->event unless $e->checkauth;
1476         return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1477
1478     if($self->api_name =~ /summary/) {
1479         my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1480         return undef unless $sum;
1481         my $obj = Fieldmapper::action::circ_chain_summary->new;
1482         $obj->$_($sum->{$_}) for keys %$sum;
1483         return $obj;
1484
1485     } else {
1486
1487         my $chain = $e->json_query({from => ['action.circ_chain', $circ_id]});
1488
1489         for my $circ_info (@$chain) {
1490             my $circ = Fieldmapper::action::circulation->new;
1491             $circ->$_($circ_info->{$_}) for keys %$circ_info;
1492             $conn->respond($circ);
1493         }
1494     }
1495
1496     return undef;
1497 }
1498
1499 __PACKAGE__->register_method(
1500         method  => "retrieve_prev_circ_chain",
1501         api_name        => "open-ils.circ.prev_renewal_chain.retrieve_by_circ",
1502     stream => 1,
1503         signature => {
1504         desc => q/Given a circulation, this returns all circulation objects
1505                 that are part of the previous chain of renewals./,
1506         params => [
1507             {desc => 'Authentication token', type => 'string'},
1508             {desc => 'Circ ID', type => 'number'},
1509         ],
1510         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1511     }
1512 );
1513
1514 __PACKAGE__->register_method(
1515         method  => "retrieve_prev_circ_chain",
1516         api_name        => "open-ils.circ.prev_renewal_chain.retrieve_by_circ.summary",
1517         signature => {
1518         desc => q/Given a circulation, this returns a summary of the circulation objects
1519                 that are part of the previous chain of renewals./,
1520         params => [
1521             {desc => 'Authentication token', type => 'string'},
1522             {desc => 'Circ ID', type => 'number'},
1523         ],
1524         return => {desc => q/Object containing Circulation Chain Summary and User Id/}
1525     }
1526 );
1527
1528 sub retrieve_prev_circ_chain {
1529     my($self, $conn, $auth, $circ_id) = @_;
1530
1531     my $e = new_editor(authtoken => $auth);
1532     return $e->event unless $e->checkauth;
1533         return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1534
1535     if($self->api_name =~ /summary/) {
1536         my $first_circ = $e->json_query({from => ['action.circ_chain', $circ_id]})->[0];
1537         my $target_copy = $$first_circ{'target_copy'};
1538         my $usr = $$first_circ{'usr'};
1539         my $last_circ_from_prev_chain = $e->json_query({
1540             'select' => {
1541                 'circ' => [{
1542                     'column' => 'id',
1543                     'transform' => 'max'
1544                 }]
1545             },
1546             'from' => 'circ', 
1547             'where' => {
1548                 target_copy => $target_copy,
1549                 id => { '<' => $$first_circ{'id'} }
1550             }
1551         })->[0];
1552         return undef unless $last_circ_from_prev_chain;
1553         return undef unless $$last_circ_from_prev_chain{'id'};
1554         my $sum = $e->json_query({from => ['action.summarize_circ_chain', $$last_circ_from_prev_chain{'id'}]})->[0];
1555         return undef unless $sum;
1556         my $obj = Fieldmapper::action::circ_chain_summary->new;
1557         $obj->$_($sum->{$_}) for keys %$sum;
1558         return { 'summary' => $obj, 'usr' => $usr };
1559
1560     } else {
1561
1562         my $first_circ = $e->json_query({from => ['action.circ_chain', $circ_id]})->[0];
1563         my $target_copy = $$first_circ{'target_copy'};
1564         my $last_circ_from_prev_chain = $e->json_query({
1565             'select' => {
1566                 'circ' => [{
1567                     'column' => 'id',
1568                     'transform' => 'max'
1569                 }]
1570             },
1571             'from' => 'circ', 
1572             'where' => {
1573                 target_copy => $target_copy,
1574                 id => { '<' => $$first_circ{'id'} }
1575             }
1576         })->[0];
1577         return undef unless $last_circ_from_prev_chain;
1578         return undef unless $$last_circ_from_prev_chain{'id'};
1579         my $chain = $e->json_query({from => ['action.circ_chain', $$last_circ_from_prev_chain{'id'}]});
1580
1581         for my $circ_info (@$chain) {
1582             my $circ = Fieldmapper::action::circulation->new;
1583             $circ->$_($circ_info->{$_}) for keys %$circ_info;
1584             $conn->respond($circ);
1585         }
1586     }
1587
1588     return undef;
1589 }
1590
1591
1592
1593
1594 # {"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}}
1595
1596
1597 1;