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