]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
if no max is configured and no valid count from the SC, default to 4, which was the...
[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
15 use DateTime;
16 use DateTime::Format::ISO8601;
17
18 use OpenILS::Application::AppUtils;
19
20 use OpenSRF::Utils qw/:datetime/;
21 use OpenILS::Utils::ModsParser;
22 use OpenILS::Event;
23 use OpenSRF::EX qw(:try);
24 use OpenSRF::Utils::Logger qw(:logger);
25 use OpenILS::Utils::Fieldmapper;
26 use OpenILS::Utils::Editor;
27 use OpenILS::Utils::CStoreEditor q/:funcs/;
28 use OpenILS::Const qw/:const/;
29 use OpenSRF::Utils::SettingsClient;
30
31 my $apputils = "OpenILS::Application::AppUtils";
32 my $U = $apputils;
33
34
35 # ------------------------------------------------------------------------
36 # Top level Circ package;
37 # ------------------------------------------------------------------------
38
39 sub initialize {
40         my $self = shift;
41         OpenILS::Application::Circ::Circulate->initialize();
42 }
43
44
45 __PACKAGE__->register_method(
46         method => 'retrieve_circ',
47         api_name        => 'open-ils.circ.retrieve',
48         signature => q/
49                 Retrieve a circ object by id
50                 @param authtoken Login session key
51                 @pararm circid The id of the circ object
52         /
53 );
54 sub retrieve_circ {
55         my( $s, $c, $a, $i ) = @_;
56         my $e = new_editor(authtoken => $a);
57         return $e->event unless $e->checkauth;
58         my $circ = $e->retrieve_action_circulation($i) or return $e->event;
59         if( $e->requestor->id ne $circ->usr ) {
60                 return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
61         }
62         return $circ;
63 }
64
65
66 __PACKAGE__->register_method(
67         method => 'fetch_circ_mods',
68         api_name => 'open-ils.circ.circ_modifier.retrieve.all');
69 sub fetch_circ_mods {
70     my($self, $conn, $args) = @_;
71     my $mods = new_editor()->retrieve_all_config_circ_modifier;
72     return [ map {$_->code} @$mods ] unless $$args{full};
73     return $mods;
74 }
75
76 __PACKAGE__->register_method(
77         method => 'fetch_bill_types',
78         api_name => 'open-ils.circ.billing_type.retrieve.all');
79 sub fetch_bill_types {
80         my $conf = OpenSRF::Utils::SettingsClient->new;
81         return $conf->config_value(
82                 'apps', 'open-ils.circ', 'app_settings', 'billing_types', 'type' );
83 }
84
85
86 # ------------------------------------------------------------------------
87 # Returns an array of {circ, record} hashes checked out by the user.
88 # ------------------------------------------------------------------------
89 __PACKAGE__->register_method(
90         method  => "checkouts_by_user",
91         api_name        => "open-ils.circ.actor.user.checked_out",
92         NOTES           => <<"  NOTES");
93         Returns a list of open circulations as a pile of objects.  each object
94         contains the relevant copy, circ, and record
95         NOTES
96
97 sub checkouts_by_user {
98         my( $self, $client, $user_session, $user_id ) = @_;
99
100         my( $requestor, $target, $copy, $record, $evt );
101
102         ( $requestor, $target, $evt ) = 
103                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
104         return $evt if $evt;
105
106         my $circs = $apputils->simplereq(
107                 'open-ils.cstore',
108                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
109                 { usr => $target->id, checkin_time => undef } );
110 #               { usr => $target->id } );
111
112         my @results;
113         for my $circ (@$circs) {
114
115                 ( $copy, $evt )  = $apputils->fetch_copy($circ->target_copy);
116                 return $evt if $evt;
117
118                 $logger->debug("Retrieving record for copy " . $circ->target_copy);
119
120                 ($record, $evt) = $apputils->fetch_record_by_copy( $circ->target_copy );
121                 return $evt if $evt;
122
123                 my $mods = $apputils->record_to_mvr($record);
124
125                 push( @results, { copy => $copy, circ => $circ, record => $mods } );
126         }
127
128         return \@results;
129
130 }
131
132
133
134 __PACKAGE__->register_method(
135         method  => "checkouts_by_user_slim",
136         api_name        => "open-ils.circ.actor.user.checked_out.slim",
137         NOTES           => <<"  NOTES");
138         Returns a list of open circulation objects
139         NOTES
140
141 # DEPRECAT ME?? XXX
142 sub checkouts_by_user_slim {
143         my( $self, $client, $user_session, $user_id ) = @_;
144
145         my( $requestor, $target, $copy, $record, $evt );
146
147         ( $requestor, $target, $evt ) = 
148                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
149         return $evt if $evt;
150
151         $logger->debug( 'User ' . $requestor->id . 
152                 " retrieving checked out items for user " . $target->id );
153
154         # XXX Make the call correct..
155         return $apputils->simplereq(
156                 'open-ils.cstore',
157                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
158                 { usr => $target->id, checkin_time => undef } );
159 #               { usr => $target->id } );
160 }
161
162
163 __PACKAGE__->register_method(
164         method  => "checkouts_by_user_opac",
165         api_name        => "open-ils.circ.actor.user.checked_out.opac",);
166
167 # XXX Deprecate Me
168 sub checkouts_by_user_opac {
169         my( $self, $client, $auth, $user_id ) = @_;
170
171         my $e = OpenILS::Utils::Editor->new( authtoken => $auth );
172         return $e->event unless $e->checkauth;
173         $user_id ||= $e->requestor->id;
174         return $e->event unless 
175                 my $patron = $e->retrieve_actor_user($user_id);
176
177         my $data;
178         my $search = {usr => $user_id, stop_fines => undef};
179
180         if( $user_id ne $e->requestor->id ) {
181                 $data = $e->search_action_circulation(
182                         $search, {checkperm=>1, permorg=>$patron->home_ou})
183                         or return $e->event;
184
185         } else {
186                 $data = $e->search_action_circulation($search);
187         }
188
189         return $data;
190 }
191
192
193 __PACKAGE__->register_method(
194         method  => "title_from_transaction",
195         api_name        => "open-ils.circ.circ_transaction.find_title",
196         NOTES           => <<"  NOTES");
197         Returns a mods object for the title that is linked to from the 
198         copy from the hold that created the given transaction
199         NOTES
200
201 sub title_from_transaction {
202         my( $self, $client, $login_session, $transactionid ) = @_;
203
204         my( $user, $circ, $title, $evt );
205
206         ( $user, $evt ) = $apputils->checkses( $login_session );
207         return $evt if $evt;
208
209         ( $circ, $evt ) = $apputils->fetch_circulation($transactionid);
210         return $evt if $evt;
211         
212         ($title, $evt) = $apputils->fetch_record_by_copy($circ->target_copy);
213         return $evt if $evt;
214
215         return $apputils->record_to_mvr($title);
216 }
217
218
219
220 __PACKAGE__->register_method(
221         method  => "new_set_circ_lost",
222         api_name        => "open-ils.circ.circulation.set_lost",
223         signature       => q/
224         Sets the copy and related open circulation to lost
225                 @param auth
226                 @param args : barcode
227         /
228 );
229
230
231 # ---------------------------------------------------------------------
232 # Sets a circulation to lost.  updates copy status to lost
233 # applies copy and/or prcoessing fees depending on org settings
234 # ---------------------------------------------------------------------
235 sub new_set_circ_lost {
236     my( $self, $conn, $auth, $args ) = @_;
237
238     my $e = new_editor(authtoken=>$auth, xact=>1);
239     return $e->die_event unless $e->checkauth;
240
241     my $barcode = $$args{barcode};
242     $logger->info("marking item lost $barcode");
243
244     # ---------------------------------------------------------------------
245     # gather the pieces
246     my $copy = $e->search_asset_copy([
247         {barcode=>$barcode, deleted=>'f'},
248         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])->[0] 
249             or return $e->die_event;
250
251     my $owning_lib = 
252         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
253             $copy->circ_lib : $copy->call_number->owning_lib;
254
255     my $circ = $e->search_action_circulation(
256         {checkin_time => undef, target_copy => $copy->id} )->[0]
257             or return $e->die_event;
258
259     $e->allowed('SET_CIRC_LOST', $circ->circ_lib) or return $e->die_event;
260
261     return OpenILS::Event->new('COPY_MARKED_LOST')
262             if $copy->status == OILS_COPY_STATUS_LOST;
263
264     # ---------------------------------------------------------------------
265     # fetch the related org settings
266     my $proc_fee = $U->ou_ancestor_setting_value(
267         $owning_lib, OILS_SETTING_LOST_PROCESSING_FEE, $e) || 0;
268     my $void_overdue = $U->ou_ancestor_setting_value(
269         $owning_lib, OILS_SETTING_VOID_OVERDUE_ON_LOST, $e) || 0;
270
271     # ---------------------------------------------------------------------
272     # move the copy into LOST status
273     $copy->status(OILS_COPY_STATUS_LOST);
274     $copy->editor($e->requestor->id);
275     $copy->edit_date('now');
276     $e->update_asset_copy($copy) or return $e->die_event;
277
278     my $price = $U->get_copy_price($e, $copy, $copy->call_number);
279
280     if( $price > 0 ) {
281         my $evt = create_bill($e, $price, 'Lost Materials', $circ->id);
282         return $evt if $evt;
283     }
284
285     # ---------------------------------------------------------------------
286     # if there is a processing fee, charge that too
287     if( $proc_fee > 0 ) {
288         my $evt = create_bill($e, $proc_fee, 'Lost Materials Processing Fee', $circ->id);
289         return $evt if $evt;
290     }
291
292     # ---------------------------------------------------------------------
293     # mark the circ as lost and stop the fines
294     $circ->stop_fines(OILS_STOP_FINES_LOST);
295     $circ->stop_fines_time('now') unless $circ->stop_fines_time;
296     $e->update_action_circulation($circ) or return $e->die_event;
297
298     # ---------------------------------------------------------------------
299     # void all overdue fines on this circ if configured
300     if( $void_overdue ) {
301         my $evt = void_overdues($e, $circ);
302         return $evt if $evt;
303     }
304
305     my $evt = reopen_xact($e, $circ->id);
306     return $evt if $evt;
307
308     $e->commit;
309     return 1;
310 }
311
312 sub reopen_xact {
313     my($e, $xactid) = @_;
314
315     # -----------------------------------------------------------------
316     # make sure the transaction is not closed
317     my $xact = $e->retrieve_money_billable_transaction($xactid)
318         or return $e->die_event;
319
320     if( $xact->xact_finish ) {
321         my ($mbts) = $U->fetch_mbts($xactid, $e);
322         if( $mbts->balance_owed != 0 ) {
323             $logger->info("* re-opening xact $xactid, orig xact_finish is ".$xact->xact_finish);
324             $xact->clear_xact_finish;
325             $e->update_money_billable_transaction($xact)
326                 or return $e->die_event;
327         } 
328     }
329
330     return undef;
331 }
332
333
334 sub create_bill {
335         my( $e, $amount, $type, $xactid ) = @_;
336
337         $logger->info("The system is charging $amount [$type] on xact $xactid");
338
339     # -----------------------------------------------------------------
340     # now create the billing
341         my $bill = Fieldmapper::money::billing->new;
342         $bill->xact($xactid);
343         $bill->amount($amount);
344         $bill->billing_type($type); 
345         $bill->note('SYSTEM GENERATED');
346     $e->create_money_billing($bill) or return $e->die_event;
347
348         return undef;
349 }
350
351
352
353 # -----------------------------------------------------------------
354 # Voids overdue fines on the given circ.  if a backdate is 
355 # provided, then we only void back to the backdate
356 # -----------------------------------------------------------------
357 sub void_overdues {
358     my( $e, $circ, $backdate ) = @_;
359
360     my $bill_search = { 
361         xact => $circ->id, 
362         billing_type => OILS_BILLING_TYPE_OVERDUE_MATERIALS 
363     };
364
365     if( $backdate ) {
366         # ------------------------------------------------------------------
367         # Fines for overdue materials are assessed up to, but not including,
368         # one fine interval after the fines are applicable.  Here, we add
369         # one fine interval to the backdate to ensure that we are not 
370         # voiding fines that were applicable before the backdate.
371         # ------------------------------------------------------------------
372
373         # if there is a raw time component (e.g. from postgres), 
374         # turn it into an interval that interval_to_seconds can parse
375         my $duration = $circ->fine_interval;
376         $duration =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
377         my $interval = OpenSRF::Utils->interval_to_seconds($duration);
378
379         my $date = DateTime::Format::ISO8601->parse_datetime($backdate);
380         $backdate = $U->epoch2ISO8601($date->epoch + $interval);
381         $logger->info("applying backdate $backdate in overdue voiding");
382         $$bill_search{billing_ts} = {'>=' => $backdate};
383     }
384
385     my $bills = $e->search_money_billing($bill_search);
386     
387     for my $bill (@$bills) {
388         next if $U->is_true($bill->voided);
389         $logger->info("voiding overdue bill ".$bill->id);
390         $bill->voided('t');
391         $bill->void_time('now');
392         $bill->voider($e->requestor->id);
393         my $n = $bill->note || "";
394         $bill->note("$n\nSystem: VOIDED FOR BACKDATE");
395         $e->update_money_billing($bill) or return $e->die_event;
396     }
397
398         return undef;
399 }
400
401
402
403
404 __PACKAGE__->register_method(
405         method  => "set_circ_claims_returned",
406         api_name        => "open-ils.circ.circulation.set_claims_returned",
407         signature       => q/
408         Sets the circ for the given item as claims returned
409         If a backdate is provided, overdue fines will be voided
410         back to the backdate
411                 @param auth
412                 @param args : barcode, backdate
413         /
414 );
415
416 sub set_circ_claims_returned {
417     my( $self, $conn, $auth, $args ) = @_;
418
419     my $e = new_editor(authtoken=>$auth, xact=>1);
420     return $e->die_event unless $e->checkauth;
421
422     my $barcode = $$args{barcode};
423     my $backdate = $$args{backdate};
424
425     $logger->info("marking circ for item $barcode as claims returned".
426         (($backdate) ? " with backdate $backdate" : ''));
427
428     my $copy = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'})->[0] 
429         or return $e->die_event;
430
431     my $circ = $e->search_action_circulation(
432         {checkin_time => undef, target_copy => $copy->id})->[0]
433             or return $e->die_event;
434
435     $e->allowed('SET_CIRC_CLAIMS_RETURNED', $circ->circ_lib) 
436         or return $e->die_event;
437
438     $circ->stop_fines(OILS_STOP_FINES_CLAIMSRETURNED);
439         $circ->stop_fines_time('now') unless $circ->stop_fines_time;
440
441     if( $backdate ) {
442         # make it look like the circ stopped at the cliams returned time
443         $circ->stop_fines_time(clense_ISO8601($backdate));
444         my $evt = void_overdues($e, $circ, $backdate);
445         return $evt if $evt;
446     }
447
448     $e->update_action_circulation($circ) or return $e->die_event;
449     $e->commit;
450     return 1;
451 }
452
453
454
455
456
457 __PACKAGE__->register_method (
458         method          => 'set_circ_due_date',
459         api_name                => 'open-ils.circ.circulation.due_date.update',
460         signature       => q/
461                 Updates the due_date on the given circ
462                 @param authtoken
463                 @param circid The id of the circ to update
464                 @param date The timestamp of the new due date
465         /
466 );
467
468 sub set_circ_due_date {
469         my( $self, $conn, $auth, $circ_id, $date ) = @_;
470
471     my $e = new_editor(xact=>1, authtoken=>$auth);
472     return $e->die_event unless $e->checkauth;
473     my $circ = $e->retrieve_action_circulation($circ_id)
474         or return $e->die_event;
475
476     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
477         $date = clense_ISO8601($date);
478         $circ->due_date($date);
479     $e->update_action_circulation($circ) or return $e->die_event;
480     $e->commit;
481
482     return $circ->id;
483 }
484
485
486 __PACKAGE__->register_method(
487         method          => "create_in_house_use",
488         api_name                => 'open-ils.circ.in_house_use.create',
489         signature       =>      q/
490                 Creates an in-house use action.
491                 @param $authtoken The login session key
492                 @param params A hash of params including
493                         'location' The org unit id where the in-house use occurs
494                         'copyid' The copy in question
495                         'count' The number of in-house uses to apply to this copy
496                 @return An array of id's representing the id's of the newly created
497                 in-house use objects or an event on an error
498         /);
499
500 __PACKAGE__->register_method(
501         method          => "create_in_house_use",
502         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
503 );
504
505
506 sub create_in_house_use {
507         my( $self, $client, $auth, $params ) = @_;
508
509         my( $evt, $copy );
510         my $org                 = $params->{location};
511         my $copyid              = $params->{copyid};
512         my $count               = $params->{count} || 1;
513         my $nc_type             = $params->{non_cat_type};
514         my $use_time    = $params->{use_time} || 'now';
515
516         my $e = new_editor(xact=>1,authtoken=>$auth);
517         return $e->event unless $e->checkauth;
518         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
519
520         my $non_cat = 1 if $self->api_name =~ /non_cat/;
521
522         unless( $non_cat ) {
523                 if( $copyid ) {
524                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
525                 } else {
526                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
527                                 or return $e->event;
528                         $copyid = $copy->id;
529                 }
530         }
531
532         if( $use_time ne 'now' ) {
533                 $use_time = clense_ISO8601($use_time);
534                 $logger->debug("in_house_use setting use time to $use_time");
535         }
536
537         my @ids;
538         for(1..$count) {
539
540                 my $ihu;
541                 my $method;
542                 my $cmeth;
543
544                 if($non_cat) {
545                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
546                         $ihu->item_type($nc_type);
547                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
548                         $cmeth = "create_action_non_cat_in_house_use";
549
550                 } else {
551                         $ihu = Fieldmapper::action::in_house_use->new;
552                         $ihu->item($copyid);
553                         $method = 'open-ils.storage.direct.action.in_house_use.create';
554                         $cmeth = "create_action_in_house_use";
555                 }
556
557                 $ihu->staff($e->requestor->id);
558                 $ihu->org_unit($org);
559                 $ihu->use_time($use_time);
560
561                 $ihu = $e->$cmeth($ihu) or return $e->event;
562                 push( @ids, $ihu->id );
563         }
564
565         $e->commit;
566         return \@ids;
567 }
568
569
570
571
572
573 __PACKAGE__->register_method(
574         method  => "view_circs",
575         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
576         notes           => q/
577                 Retrieves the last X circs for a given copy
578                 @param authtoken The login session key
579                 @param copyid The copy to check
580                 @param count How far to go back in the item history
581                 @return An array of circ ids
582         /);
583
584 # ----------------------------------------------------------------------
585 # Returns $count most recent circs.  If count exceeds the configured 
586 # max, use the configured max instead
587 # ----------------------------------------------------------------------
588 sub view_circs {
589         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
590
591     my $e = new_editor(authtoken => $authtoken);
592     return $e->event unless $e->checkauth;
593     
594     my $copy = $e->retrieve_asset_copy([
595         $copyid,
596         {   flesh => 1,
597             flesh_fields => {acp => ['call_number']}
598         }
599     ]) or return $e->event;
600
601     return $e->event unless $e->allowed(
602         'VIEW_COPY_CHECKOUT_HISTORY', 
603         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
604             $copy->circ_lib : $copy->call_number->owning_lib);
605         
606     my $max_history = $U->ou_ancestor_setting_value(
607         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
608
609     if(defined $max_history) {
610         $count = $max_history unless defined $count and $count < $max_history;
611     } else {
612         $count = 4 unless defined $count;
613     }
614
615     return $e->search_action_circulation([
616         {target_copy => $copyid}, 
617         {limit => $count, order_by => { circ => "xact_start DESC" }} 
618     ]);
619 }
620
621
622 __PACKAGE__->register_method(
623         method  => "circ_count",
624         api_name        => "open-ils.circ.circulation.count",
625         notes           => q/
626                 Returns the number of times the item has circulated
627                 @param copyid The copy to check
628         /);
629
630 sub circ_count {
631         my( $self, $client, $copyid, $range ) = @_; 
632         my $e = OpenILS::Utils::Editor->new;
633         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
634 }
635
636
637
638 __PACKAGE__->register_method(
639         method          => 'fetch_notes',
640         api_name                => 'open-ils.circ.copy_note.retrieve.all',
641         signature       => q/
642                 Returns an array of copy note objects.  
643                 @param args A named hash of parameters including:
644                         authtoken       : Required if viewing non-public notes
645                         itemid          : The id of the item whose notes we want to retrieve
646                         pub                     : True if all the caller wants are public notes
647                 @return An array of note objects
648         /);
649
650 __PACKAGE__->register_method(
651         method          => 'fetch_notes',
652         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
653         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
654
655 __PACKAGE__->register_method(
656         method          => 'fetch_notes',
657         api_name                => 'open-ils.circ.title_note.retrieve.all',
658         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
659
660
661 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
662 sub fetch_notes {
663         my( $self, $connection, $args ) = @_;
664
665         my $id = $$args{itemid};
666         my $authtoken = $$args{authtoken};
667         my( $r, $evt);
668
669         if( $self->api_name =~ /copy/ ) {
670                 if( $$args{pub} ) {
671                         return $U->cstorereq(
672                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
673                                 { owning_copy => $id, pub => 't' } );
674                 } else {
675                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
676                         return $evt if $evt;
677                         return $U->cstorereq(
678                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
679                 }
680
681         } elsif( $self->api_name =~ /call_number/ ) {
682                 if( $$args{pub} ) {
683                         return $U->cstorereq(
684                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
685                                 { call_number => $id, pub => 't' } );
686                 } else {
687                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
688                         return $evt if $evt;
689                         return $U->cstorereq(
690                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
691                 }
692
693         } elsif( $self->api_name =~ /title/ ) {
694                 if( $$args{pub} ) {
695                         return $U->cstorereq(
696                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
697                                 { record => $id, pub => 't' } );
698                 } else {
699                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
700                         return $evt if $evt;
701                         return $U->cstorereq(
702                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
703                 }
704         }
705
706         return undef;
707 }
708
709 __PACKAGE__->register_method(
710         method  => 'has_notes',
711         api_name        => 'open-ils.circ.copy.has_notes');
712 __PACKAGE__->register_method(
713         method  => 'has_notes',
714         api_name        => 'open-ils.circ.call_number.has_notes');
715 __PACKAGE__->register_method(
716         method  => 'has_notes',
717         api_name        => 'open-ils.circ.title.has_notes');
718
719
720 sub has_notes {
721         my( $self, $conn, $authtoken, $id ) = @_;
722         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
723         return $editor->event unless $editor->checkauth;
724
725         my $n = $editor->search_asset_copy_note(
726                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
727
728         $n = $editor->search_asset_call_number_note(
729                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
730
731         $n = $editor->search_biblio_record_note(
732                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
733
734         return scalar @$n;
735 }
736
737
738
739 __PACKAGE__->register_method(
740         method          => 'create_copy_note',
741         api_name                => 'open-ils.circ.copy_note.create',
742         signature       => q/
743                 Creates a new copy note
744                 @param authtoken The login session key
745                 @param note     The note object to create
746                 @return The id of the new note object
747         /);
748
749 sub create_copy_note {
750         my( $self, $connection, $authtoken, $note ) = @_;
751
752         my $e = new_editor(xact=>1, authtoken=>$authtoken);
753         return $e->event unless $e->checkauth;
754         my $copy = $e->retrieve_asset_copy(
755                 [
756                         $note->owning_copy,
757                         {       flesh => 1,
758                                 flesh_fields => { 'acp' => ['call_number'] }
759                         }
760                 ]
761         );
762
763         return $e->event unless 
764                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
765
766         $note->create_date('now');
767         $note->creator($e->requestor->id);
768         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
769         $note->clear_id;
770
771         $e->create_asset_copy_note($note) or return $e->event;
772         $e->commit;
773         return $note->id;
774 }
775
776
777 __PACKAGE__->register_method(
778         method          => 'delete_copy_note',
779         api_name                =>      'open-ils.circ.copy_note.delete',
780         signature       => q/
781                 Deletes an existing copy note
782                 @param authtoken The login session key
783                 @param noteid The id of the note to delete
784                 @return 1 on success - Event otherwise.
785                 /);
786 sub delete_copy_note {
787         my( $self, $conn, $authtoken, $noteid ) = @_;
788
789         my $e = new_editor(xact=>1, authtoken=>$authtoken);
790         return $e->die_event unless $e->checkauth;
791
792         my $note = $e->retrieve_asset_copy_note([
793                 $noteid,
794                 { flesh => 2,
795                         flesh_fields => {
796                                 'acpn' => [ 'owning_copy' ],
797                                 'acp' => [ 'call_number' ],
798                         }
799                 }
800         ]) or return $e->die_event;
801
802         if( $note->creator ne $e->requestor->id ) {
803                 return $e->die_event unless 
804                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
805         }
806
807         $e->delete_asset_copy_note($note) or return $e->die_event;
808         $e->commit;
809         return 1;
810 }
811
812
813 __PACKAGE__->register_method(
814         method => 'age_hold_rules',
815         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
816 );
817
818 sub age_hold_rules {
819         my( $self, $conn ) = @_;
820         return new_editor()->retrieve_all_config_rules_age_hold_protect();
821 }
822
823
824
825 __PACKAGE__->register_method(
826         method => 'copy_details_barcode',
827     authoritative => 1,
828         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
829 sub copy_details_barcode {
830         my( $self, $conn, $auth, $barcode ) = @_;
831     my $e = new_editor();
832     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
833     return $e->event unless $cid;
834         return copy_details( $self, $conn, $auth, $cid );
835 }
836
837
838 __PACKAGE__->register_method(
839         method => 'copy_details',
840         api_name => 'open-ils.circ.copy_details.retrieve');
841
842 sub copy_details {
843         my( $self, $conn, $auth, $copy_id ) = @_;
844         my $e = new_editor(authtoken=>$auth);
845         return $e->event unless $e->checkauth;
846
847         my $flesh = { flesh => 1 };
848
849         my $copy = $e->retrieve_asset_copy(
850                 [
851                         $copy_id,
852                         {
853                                 flesh => 2,
854                                 flesh_fields => {
855                                         acp => ['call_number'],
856                                         acn => ['record']
857                                 }
858                         }
859                 ]) or return $e->event;
860
861
862         # De-flesh the copy for backwards compatibility
863         my $mvr;
864         my $vol = $copy->call_number;
865         if( ref $vol ) {
866                 $copy->call_number($vol->id);
867                 my $record = $vol->record;
868                 if( ref $record ) {
869                         $vol->record($record->id);
870                         $mvr = $U->record_to_mvr($record);
871                 }
872         }
873
874
875         my $hold = $e->search_action_hold_request(
876                 { 
877                         current_copy            => $copy_id, 
878                         capture_time            => { "!=" => undef },
879                         fulfillment_time        => undef,
880                         cancel_time                     => undef,
881                 }
882         )->[0];
883
884         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
885
886         my $transit = $e->search_action_transit_copy(
887                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
888
889         # find the latest circ, open or closed
890         my $circ = $e->search_action_circulation(
891                 [
892                         { target_copy => $copy_id },
893                         { order_by => { circ => 'xact_start desc' }, limit => 1 }
894                 ]
895         )->[0];
896
897
898         return {
899                 copy            => $copy,
900                 hold            => $hold,
901                 transit => $transit,
902                 circ            => $circ,
903                 volume  => $vol,
904                 mvr             => $mvr,
905         };
906 }
907
908
909
910
911 __PACKAGE__->register_method(
912         method => 'mark_item',
913         api_name => 'open-ils.circ.mark_item_damaged',
914 );
915 __PACKAGE__->register_method(
916         method => 'mark_item',
917         api_name => 'open-ils.circ.mark_item_missing',
918 );
919
920 sub mark_item {
921         my( $self, $conn, $auth, $copy_id ) = @_;
922         my $e = new_editor(authtoken=>$auth, xact =>1);
923         return $e->event unless $e->checkauth;
924
925         my $perm = 'MARK_ITEM_MISSING';
926         my $stat = OILS_COPY_STATUS_MISSING;
927
928         if( $self->api_name =~ /damaged/ ) {
929                 $perm = 'MARK_ITEM_DAMAGED';
930                 $stat = OILS_COPY_STATUS_DAMAGED;
931         }
932
933         my $copy = $e->retrieve_asset_copy($copy_id)
934                 or return $e->event;
935         $copy->status($stat);
936         $copy->edit_date('now');
937         $copy->editor($e->requestor->id);
938
939         $e->update_asset_copy($copy) or return $e->event;
940
941
942         my $holds = $e->search_action_hold_request(
943                 { 
944                         current_copy => $copy->id,
945                         fulfillment_time => undef,
946                         cancel_time => undef,
947                 }
948         );
949
950         $e->commit;
951
952         $logger->debug("reseting holds that target the marked copy");
953         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
954
955         return 1;
956 }
957
958
959
960
961
962
963 # ----------------------------------------------------------------------
964 __PACKAGE__->register_method(
965         method => 'magic_fetch',
966         api_name => 'open-ils.agent.fetch'
967 );
968
969 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
970
971 sub magic_fetch {
972         my( $self, $conn, $auth, $args ) = @_;
973         my $e = new_editor( authtoken => $auth );
974         return $e->event unless $e->checkauth;
975
976         my $hint = $$args{hint};
977         my $id  = $$args{id};
978
979         # Is the call allowed to fetch this type of object?
980         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
981
982         # Find the class the iplements the given hint
983         my ($class) = grep { 
984                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
985
986         $class =~ s/Fieldmapper:://og;
987         $class =~ s/::/_/og;
988         my $method = "retrieve_$class";
989
990         my $obj = $e->$method($id) or return $e->event;
991         return $obj;
992 }
993 # ----------------------------------------------------------------------
994
995
996 __PACKAGE__->register_method(
997         method  => "fleshed_circ_retrieve",
998     authoritative => 1,
999         api_name        => "open-ils.circ.fleshed.retrieve",);
1000
1001 sub fleshed_circ_retrieve {
1002         my( $self, $client, $id ) = @_;
1003         my $e = new_editor();
1004         my $circ = $e->retrieve_action_circulation(
1005                 [
1006                         $id,
1007                         { 
1008                                 flesh                           => 4,
1009                                 flesh_fields    => { 
1010                                         circ => [ qw/ target_copy / ],
1011                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1012                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1013                                         acn => [ qw/ record / ],
1014                                 }
1015                         }
1016                 ]
1017         ) or return $e->event;
1018         
1019         my $copy = $circ->target_copy;
1020         my $vol = $copy->call_number;
1021         my $rec = $circ->target_copy->call_number->record;
1022
1023         $vol->record($rec->id);
1024         $copy->call_number($vol->id);
1025         $circ->target_copy($copy->id);
1026
1027         my $mvr;
1028
1029         if( $rec->id == OILS_PRECAT_RECORD ) {
1030                 $rec = undef;
1031                 $vol = undef;
1032         } else { 
1033                 $mvr = $U->record_to_mvr($rec);
1034                 $rec->marc(''); # drop the bulky marc data
1035         }
1036
1037         return {
1038                 circ => $circ,
1039                 copy => $copy,
1040                 volume => $vol,
1041                 record => $rec,
1042                 mvr => $mvr,
1043         };
1044 }
1045
1046 # {"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}}
1047
1048
1049 1;