]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
fixed perm check. also, if no count is provided, falls back to configured max
[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 == 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 $default_price = $U->ou_ancestor_setting_value(
267         $owning_lib, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
268     my $proc_fee = $U->ou_ancestor_setting_value(
269         $owning_lib, OILS_SETTING_LOST_PROCESSING_FEE, $e) || 0;
270     my $charge_on_0 = $U->ou_ancestor_setting_value(
271         $owning_lib, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
272     my $void_overdue = $U->ou_ancestor_setting_value(
273         $owning_lib, OILS_SETTING_VOID_OVERDUE_ON_LOST, $e) || 0;
274
275     $logger->info("org settings: default price = $default_price, ".
276         "processing fee = $proc_fee, charge on 0 = $charge_on_0, void overdues = $void_overdue");
277
278     # ---------------------------------------------------------------------
279     # move the copy into LOST status
280     $copy->status(OILS_COPY_STATUS_LOST);
281     $copy->editor($e->requestor->id);
282     $copy->edit_date('now');
283     $e->update_asset_copy($copy) or return $e->die_event;
284
285     # ---------------------------------------------------------------------
286     # determine the appropriate item price to charge and create the billing
287     my $price = $copy->price;
288     $price = $default_price unless defined $price;
289     $price = 0 if $price < 0;
290     $price = $default_price if $price == 0 and $charge_on_0;
291
292     if( $price > 0 ) {
293         my $evt = create_bill($e, $price, 'Lost Materials', $circ->id);
294         return $evt if $evt;
295     }
296
297     # ---------------------------------------------------------------------
298     # if there is a processing fee, charge that too
299     if( $proc_fee > 0 ) {
300         my $evt = create_bill($e, $proc_fee, 'Lost Materials Processing Fee', $circ->id);
301         return $evt if $evt;
302     }
303
304     # ---------------------------------------------------------------------
305     # mark the circ as lost and stop the fines
306     $circ->stop_fines(OILS_STOP_FINES_LOST);
307     $circ->stop_fines_time('now') unless $circ->stop_fines_time;
308     $e->update_action_circulation($circ) or return $e->die_event;
309
310     # ---------------------------------------------------------------------
311     # void all overdue fines on this circ if configured
312     if( $void_overdue ) {
313         my $evt = void_overdues($e, $circ);
314         return $evt if $evt;
315     }
316
317     my $evt = reopen_xact($e, $circ->id);
318     return $evt if $evt;
319
320     $e->commit;
321     return 1;
322 }
323
324 sub reopen_xact {
325     my($e, $xactid) = @_;
326
327     # -----------------------------------------------------------------
328     # make sure the transaction is not closed
329     my $xact = $e->retrieve_money_billable_transaction($xactid)
330         or return $e->die_event;
331
332     if( $xact->xact_finish ) {
333         my ($mbts) = $U->fetch_mbts($xactid, $e);
334         if( $mbts->balance_owed != 0 ) {
335             $logger->info("* re-opening xact $xactid, orig xact_finish is ".$xact->xact_finish);
336             $xact->clear_xact_finish;
337             $e->update_money_billable_transaction($xact)
338                 or return $e->die_event;
339         } 
340     }
341
342     return undef;
343 }
344
345
346 sub create_bill {
347         my( $e, $amount, $type, $xactid ) = @_;
348
349         $logger->info("The system is charging $amount [$type] on xact $xactid");
350
351     # -----------------------------------------------------------------
352     # now create the billing
353         my $bill = Fieldmapper::money::billing->new;
354         $bill->xact($xactid);
355         $bill->amount($amount);
356         $bill->billing_type($type); 
357         $bill->note('SYSTEM GENERATED');
358     $e->create_money_billing($bill) or return $e->die_event;
359
360         return undef;
361 }
362
363
364
365 # -----------------------------------------------------------------
366 # Voids overdue fines on the given circ.  if a backdate is 
367 # provided, then we only void back to the backdate
368 # -----------------------------------------------------------------
369 sub void_overdues {
370     my( $e, $circ, $backdate ) = @_;
371
372     my $bill_search = { 
373         xact => $circ->id, 
374         billing_type => OILS_BILLING_TYPE_OVERDUE_MATERIALS 
375     };
376
377     if( $backdate ) {
378         # ------------------------------------------------------------------
379         # Fines for overdue materials are assessed up to, but not including,
380         # one fine interval after the fines are applicable.  Here, we add
381         # one fine interval to the backdate to ensure that we are not 
382         # voiding fines that were applicable before the backdate.
383         # ------------------------------------------------------------------
384
385         # if there is a raw time component (e.g. from postgres), 
386         # turn it into an interval that interval_to_seconds can parse
387         my $duration = $circ->fine_interval;
388         $duration =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
389         my $interval = OpenSRF::Utils->interval_to_seconds($duration);
390
391         my $date = DateTime::Format::ISO8601->parse_datetime($backdate);
392         $backdate = $U->epoch2ISO8601($date->epoch + $interval);
393         $logger->info("applying backdate $backdate in overdue voiding");
394         $$bill_search{billing_ts} = {'>=' => $backdate};
395     }
396
397     my $bills = $e->search_money_billing($bill_search);
398     
399     for my $bill (@$bills) {
400         next if $U->is_true($bill->voided);
401         $logger->info("voiding overdue bill ".$bill->id);
402         $bill->voided('t');
403         $bill->void_time('now');
404         $bill->voider($e->requestor->id);
405         my $n = $bill->note || "";
406         $bill->note("$n\nSystem: VOIDED FOR BACKDATE");
407         $e->update_money_billing($bill) or return $e->die_event;
408     }
409
410         return undef;
411 }
412
413
414
415
416 __PACKAGE__->register_method(
417         method  => "set_circ_claims_returned",
418         api_name        => "open-ils.circ.circulation.set_claims_returned",
419         signature       => q/
420         Sets the circ for the given item as claims returned
421         If a backdate is provided, overdue fines will be voided
422         back to the backdate
423                 @param auth
424                 @param args : barcode, backdate
425         /
426 );
427
428 sub set_circ_claims_returned {
429     my( $self, $conn, $auth, $args ) = @_;
430
431     my $e = new_editor(authtoken=>$auth, xact=>1);
432     return $e->die_event unless $e->checkauth;
433
434     my $barcode = $$args{barcode};
435     my $backdate = $$args{backdate};
436
437     $logger->info("marking circ for item $barcode as claims returned".
438         (($backdate) ? " with backdate $backdate" : ''));
439
440     my $copy = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'})->[0] 
441         or return $e->die_event;
442
443     my $circ = $e->search_action_circulation(
444         {checkin_time => undef, target_copy => $copy->id})->[0]
445             or return $e->die_event;
446
447     $e->allowed('SET_CIRC_CLAIMS_RETURNED', $circ->circ_lib) 
448         or return $e->die_event;
449
450     $circ->stop_fines(OILS_STOP_FINES_CLAIMSRETURNED);
451         $circ->stop_fines_time('now') unless $circ->stop_fines_time;
452
453     if( $backdate ) {
454         # make it look like the circ stopped at the cliams returned time
455         $circ->stop_fines_time(clense_ISO8601($backdate));
456         my $evt = void_overdues($e, $circ, $backdate);
457         return $evt if $evt;
458     }
459
460     $e->update_action_circulation($circ) or return $e->die_event;
461     $e->commit;
462     return 1;
463 }
464
465
466
467
468
469 __PACKAGE__->register_method (
470         method          => 'set_circ_due_date',
471         api_name                => 'open-ils.circ.circulation.due_date.update',
472         signature       => q/
473                 Updates the due_date on the given circ
474                 @param authtoken
475                 @param circid The id of the circ to update
476                 @param date The timestamp of the new due date
477         /
478 );
479
480 sub set_circ_due_date {
481         my( $self, $conn, $auth, $circ_id, $date ) = @_;
482
483     my $e = new_editor(xact=>1, authtoken=>$auth);
484     return $e->die_event unless $e->checkauth;
485     my $circ = $e->retrieve_action_circulation($circ_id)
486         or return $e->die_event;
487
488     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
489         $date = clense_ISO8601($date);
490         $circ->due_date($date);
491     $e->update_action_circulation($circ) or return $e->die_event;
492     $e->commit;
493
494     return $circ->id;
495 }
496
497
498 __PACKAGE__->register_method(
499         method          => "create_in_house_use",
500         api_name                => 'open-ils.circ.in_house_use.create',
501         signature       =>      q/
502                 Creates an in-house use action.
503                 @param $authtoken The login session key
504                 @param params A hash of params including
505                         'location' The org unit id where the in-house use occurs
506                         'copyid' The copy in question
507                         'count' The number of in-house uses to apply to this copy
508                 @return An array of id's representing the id's of the newly created
509                 in-house use objects or an event on an error
510         /);
511
512 __PACKAGE__->register_method(
513         method          => "create_in_house_use",
514         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
515 );
516
517
518 sub create_in_house_use {
519         my( $self, $client, $auth, $params ) = @_;
520
521         my( $evt, $copy );
522         my $org                 = $params->{location};
523         my $copyid              = $params->{copyid};
524         my $count               = $params->{count} || 1;
525         my $nc_type             = $params->{non_cat_type};
526         my $use_time    = $params->{use_time} || 'now';
527
528         my $e = new_editor(xact=>1,authtoken=>$auth);
529         return $e->event unless $e->checkauth;
530         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
531
532         my $non_cat = 1 if $self->api_name =~ /non_cat/;
533
534         unless( $non_cat ) {
535                 if( $copyid ) {
536                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
537                 } else {
538                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
539                                 or return $e->event;
540                         $copyid = $copy->id;
541                 }
542         }
543
544         if( $use_time ne 'now' ) {
545                 $use_time = clense_ISO8601($use_time);
546                 $logger->debug("in_house_use setting use time to $use_time");
547         }
548
549         my @ids;
550         for(1..$count) {
551
552                 my $ihu;
553                 my $method;
554                 my $cmeth;
555
556                 if($non_cat) {
557                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
558                         $ihu->item_type($nc_type);
559                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
560                         $cmeth = "create_action_non_cat_in_house_use";
561
562                 } else {
563                         $ihu = Fieldmapper::action::in_house_use->new;
564                         $ihu->item($copyid);
565                         $method = 'open-ils.storage.direct.action.in_house_use.create';
566                         $cmeth = "create_action_in_house_use";
567                 }
568
569                 $ihu->staff($e->requestor->id);
570                 $ihu->org_unit($org);
571                 $ihu->use_time($use_time);
572
573                 $ihu = $e->$cmeth($ihu) or return $e->event;
574                 push( @ids, $ihu->id );
575         }
576
577         $e->commit;
578         return \@ids;
579 }
580
581
582
583
584
585 __PACKAGE__->register_method(
586         method  => "view_circs",
587         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
588         notes           => q/
589                 Retrieves the last X circs for a given copy
590                 @param authtoken The login session key
591                 @param copyid The copy to check
592                 @param count How far to go back in the item history
593                 @return An array of circ ids
594         /);
595
596 # ----------------------------------------------------------------------
597 # Returns $count most recent circs.  If count exceeds the configured 
598 # max, use the configured max instead
599 # ----------------------------------------------------------------------
600 sub view_circs {
601         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
602
603     my $e = new_editor(authtoken => $authtoken);
604     return $e->event unless $e->checkauth;
605     
606     my $copy = $e->retrieve_asset_copy([
607         $copyid,
608         {   flesh => 1,
609             flesh_fields => {acp => ['call_number']}
610         }
611     ]) or return $e->event;
612
613     return $e->event unless $e->allowed(
614         'VIEW_COPY_CHECKOUT_HISTORY', 
615         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
616             $copy->circ_lib : $copy->call_number->owning_lib);
617         
618     my $max_history = $U->ou_ancestor_setting_value(
619         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
620
621     $count = $max_history if $max_history and (!$count or $count > $max_history);
622
623         return [] unless $count;
624
625     return $e->search_action_circulation([
626         {target_copy => $copyid}, 
627         {limit => $count, order_by => { circ => "xact_start DESC" }} 
628     ]);
629 }
630
631
632 __PACKAGE__->register_method(
633         method  => "circ_count",
634         api_name        => "open-ils.circ.circulation.count",
635         notes           => q/
636                 Returns the number of times the item has circulated
637                 @param copyid The copy to check
638         /);
639
640 sub circ_count {
641         my( $self, $client, $copyid, $range ) = @_; 
642         my $e = OpenILS::Utils::Editor->new;
643         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
644 }
645
646
647
648 __PACKAGE__->register_method(
649         method          => 'fetch_notes',
650         api_name                => 'open-ils.circ.copy_note.retrieve.all',
651         signature       => q/
652                 Returns an array of copy note objects.  
653                 @param args A named hash of parameters including:
654                         authtoken       : Required if viewing non-public notes
655                         itemid          : The id of the item whose notes we want to retrieve
656                         pub                     : True if all the caller wants are public notes
657                 @return An array of note objects
658         /);
659
660 __PACKAGE__->register_method(
661         method          => 'fetch_notes',
662         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
663         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
664
665 __PACKAGE__->register_method(
666         method          => 'fetch_notes',
667         api_name                => 'open-ils.circ.title_note.retrieve.all',
668         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
669
670
671 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
672 sub fetch_notes {
673         my( $self, $connection, $args ) = @_;
674
675         my $id = $$args{itemid};
676         my $authtoken = $$args{authtoken};
677         my( $r, $evt);
678
679         if( $self->api_name =~ /copy/ ) {
680                 if( $$args{pub} ) {
681                         return $U->cstorereq(
682                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
683                                 { owning_copy => $id, pub => 't' } );
684                 } else {
685                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
686                         return $evt if $evt;
687                         return $U->cstorereq(
688                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
689                 }
690
691         } elsif( $self->api_name =~ /call_number/ ) {
692                 if( $$args{pub} ) {
693                         return $U->cstorereq(
694                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
695                                 { call_number => $id, pub => 't' } );
696                 } else {
697                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
698                         return $evt if $evt;
699                         return $U->cstorereq(
700                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
701                 }
702
703         } elsif( $self->api_name =~ /title/ ) {
704                 if( $$args{pub} ) {
705                         return $U->cstorereq(
706                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
707                                 { record => $id, pub => 't' } );
708                 } else {
709                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
710                         return $evt if $evt;
711                         return $U->cstorereq(
712                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
713                 }
714         }
715
716         return undef;
717 }
718
719 __PACKAGE__->register_method(
720         method  => 'has_notes',
721         api_name        => 'open-ils.circ.copy.has_notes');
722 __PACKAGE__->register_method(
723         method  => 'has_notes',
724         api_name        => 'open-ils.circ.call_number.has_notes');
725 __PACKAGE__->register_method(
726         method  => 'has_notes',
727         api_name        => 'open-ils.circ.title.has_notes');
728
729
730 sub has_notes {
731         my( $self, $conn, $authtoken, $id ) = @_;
732         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
733         return $editor->event unless $editor->checkauth;
734
735         my $n = $editor->search_asset_copy_note(
736                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
737
738         $n = $editor->search_asset_call_number_note(
739                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
740
741         $n = $editor->search_biblio_record_note(
742                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
743
744         return scalar @$n;
745 }
746
747
748
749 __PACKAGE__->register_method(
750         method          => 'create_copy_note',
751         api_name                => 'open-ils.circ.copy_note.create',
752         signature       => q/
753                 Creates a new copy note
754                 @param authtoken The login session key
755                 @param note     The note object to create
756                 @return The id of the new note object
757         /);
758
759 sub create_copy_note {
760         my( $self, $connection, $authtoken, $note ) = @_;
761
762         my $e = new_editor(xact=>1, authtoken=>$authtoken);
763         return $e->event unless $e->checkauth;
764         my $copy = $e->retrieve_asset_copy(
765                 [
766                         $note->owning_copy,
767                         {       flesh => 1,
768                                 flesh_fields => { 'acp' => ['call_number'] }
769                         }
770                 ]
771         );
772
773         return $e->event unless 
774                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
775
776         $note->create_date('now');
777         $note->creator($e->requestor->id);
778         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
779         $note->clear_id;
780
781         $e->create_asset_copy_note($note) or return $e->event;
782         $e->commit;
783         return $note->id;
784 }
785
786
787 __PACKAGE__->register_method(
788         method          => 'delete_copy_note',
789         api_name                =>      'open-ils.circ.copy_note.delete',
790         signature       => q/
791                 Deletes an existing copy note
792                 @param authtoken The login session key
793                 @param noteid The id of the note to delete
794                 @return 1 on success - Event otherwise.
795                 /);
796 sub delete_copy_note {
797         my( $self, $conn, $authtoken, $noteid ) = @_;
798
799         my $e = new_editor(xact=>1, authtoken=>$authtoken);
800         return $e->die_event unless $e->checkauth;
801
802         my $note = $e->retrieve_asset_copy_note([
803                 $noteid,
804                 { flesh => 2,
805                         flesh_fields => {
806                                 'acpn' => [ 'owning_copy' ],
807                                 'acp' => [ 'call_number' ],
808                         }
809                 }
810         ]) or return $e->die_event;
811
812         if( $note->creator ne $e->requestor->id ) {
813                 return $e->die_event unless 
814                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
815         }
816
817         $e->delete_asset_copy_note($note) or return $e->die_event;
818         $e->commit;
819         return 1;
820 }
821
822
823 __PACKAGE__->register_method(
824         method => 'age_hold_rules',
825         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
826 );
827
828 sub age_hold_rules {
829         my( $self, $conn ) = @_;
830         return new_editor()->retrieve_all_config_rules_age_hold_protect();
831 }
832
833
834
835 __PACKAGE__->register_method(
836         method => 'copy_details_barcode',
837     authoritative => 1,
838         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
839 sub copy_details_barcode {
840         my( $self, $conn, $auth, $barcode ) = @_;
841     my $e = new_editor();
842     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
843     return $e->event unless $cid;
844         return copy_details( $self, $conn, $auth, $cid );
845 }
846
847
848 __PACKAGE__->register_method(
849         method => 'copy_details',
850         api_name => 'open-ils.circ.copy_details.retrieve');
851
852 sub copy_details {
853         my( $self, $conn, $auth, $copy_id ) = @_;
854         my $e = new_editor(authtoken=>$auth);
855         return $e->event unless $e->checkauth;
856
857         my $flesh = { flesh => 1 };
858
859         my $copy = $e->retrieve_asset_copy(
860                 [
861                         $copy_id,
862                         {
863                                 flesh => 2,
864                                 flesh_fields => {
865                                         acp => ['call_number'],
866                                         acn => ['record']
867                                 }
868                         }
869                 ]) or return $e->event;
870
871
872         # De-flesh the copy for backwards compatibility
873         my $mvr;
874         my $vol = $copy->call_number;
875         if( ref $vol ) {
876                 $copy->call_number($vol->id);
877                 my $record = $vol->record;
878                 if( ref $record ) {
879                         $vol->record($record->id);
880                         $mvr = $U->record_to_mvr($record);
881                 }
882         }
883
884
885         my $hold = $e->search_action_hold_request(
886                 { 
887                         current_copy            => $copy_id, 
888                         capture_time            => { "!=" => undef },
889                         fulfillment_time        => undef,
890                         cancel_time                     => undef,
891                 }
892         )->[0];
893
894         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
895
896         my $transit = $e->search_action_transit_copy(
897                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
898
899         # find the latest circ, open or closed
900         my $circ = $e->search_action_circulation(
901                 [
902                         { target_copy => $copy_id },
903                         { order_by => { circ => 'xact_start desc' }, limit => 1 }
904                 ]
905         )->[0];
906
907
908         return {
909                 copy            => $copy,
910                 hold            => $hold,
911                 transit => $transit,
912                 circ            => $circ,
913                 volume  => $vol,
914                 mvr             => $mvr,
915         };
916 }
917
918
919
920
921 __PACKAGE__->register_method(
922         method => 'mark_item',
923         api_name => 'open-ils.circ.mark_item_damaged',
924 );
925 __PACKAGE__->register_method(
926         method => 'mark_item',
927         api_name => 'open-ils.circ.mark_item_missing',
928 );
929
930 sub mark_item {
931         my( $self, $conn, $auth, $copy_id ) = @_;
932         my $e = new_editor(authtoken=>$auth, xact =>1);
933         return $e->event unless $e->checkauth;
934
935         my $perm = 'MARK_ITEM_MISSING';
936         my $stat = OILS_COPY_STATUS_MISSING;
937
938         if( $self->api_name =~ /damaged/ ) {
939                 $perm = 'MARK_ITEM_DAMAGED';
940                 $stat = OILS_COPY_STATUS_DAMAGED;
941         }
942
943         my $copy = $e->retrieve_asset_copy($copy_id)
944                 or return $e->event;
945         $copy->status($stat);
946         $copy->edit_date('now');
947         $copy->editor($e->requestor->id);
948
949         $e->update_asset_copy($copy) or return $e->event;
950
951
952         my $holds = $e->search_action_hold_request(
953                 { 
954                         current_copy => $copy->id,
955                         fulfillment_time => undef,
956                         cancel_time => undef,
957                 }
958         );
959
960         $e->commit;
961
962         $logger->debug("reseting holds that target the marked copy");
963         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
964
965         return 1;
966 }
967
968
969
970
971
972
973 # ----------------------------------------------------------------------
974 __PACKAGE__->register_method(
975         method => 'magic_fetch',
976         api_name => 'open-ils.agent.fetch'
977 );
978
979 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
980
981 sub magic_fetch {
982         my( $self, $conn, $auth, $args ) = @_;
983         my $e = new_editor( authtoken => $auth );
984         return $e->event unless $e->checkauth;
985
986         my $hint = $$args{hint};
987         my $id  = $$args{id};
988
989         # Is the call allowed to fetch this type of object?
990         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
991
992         # Find the class the iplements the given hint
993         my ($class) = grep { 
994                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
995
996         $class =~ s/Fieldmapper:://og;
997         $class =~ s/::/_/og;
998         my $method = "retrieve_$class";
999
1000         my $obj = $e->$method($id) or return $e->event;
1001         return $obj;
1002 }
1003 # ----------------------------------------------------------------------
1004
1005
1006 __PACKAGE__->register_method(
1007         method  => "fleshed_circ_retrieve",
1008     authoritative => 1,
1009         api_name        => "open-ils.circ.fleshed.retrieve",);
1010
1011 sub fleshed_circ_retrieve {
1012         my( $self, $client, $id ) = @_;
1013         my $e = new_editor();
1014         my $circ = $e->retrieve_action_circulation(
1015                 [
1016                         $id,
1017                         { 
1018                                 flesh                           => 4,
1019                                 flesh_fields    => { 
1020                                         circ => [ qw/ target_copy / ],
1021                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1022                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1023                                         acn => [ qw/ record / ],
1024                                 }
1025                         }
1026                 ]
1027         ) or return $e->event;
1028         
1029         my $copy = $circ->target_copy;
1030         my $vol = $copy->call_number;
1031         my $rec = $circ->target_copy->call_number->record;
1032
1033         $vol->record($rec->id);
1034         $copy->call_number($vol->id);
1035         $circ->target_copy($copy->id);
1036
1037         my $mvr;
1038
1039         if( $rec->id == OILS_PRECAT_RECORD ) {
1040                 $rec = undef;
1041                 $vol = undef;
1042         } else { 
1043                 $mvr = $U->record_to_mvr($rec);
1044                 $rec->marc(''); # drop the bulky marc data
1045         }
1046
1047         return {
1048                 circ => $circ,
1049                 copy => $copy,
1050                 volume => $vol,
1051                 record => $rec,
1052                 mvr => $mvr,
1053         };
1054 }
1055
1056 # {"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}}
1057
1058
1059 1;