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