Bug 25348: Add support for circulation status 12 ( lost )
[koha.git] / C4 / SIP / ILS / Item.pm
1 #
2 # ILS::Item.pm
3
4 # A Class for hiding the ILS's concept of the item from OpenSIP
5 #
6
7 package C4::SIP::ILS::Item;
8
9 use strict;
10 use warnings;
11
12 use C4::SIP::Sip qw(siplog);
13 use Carp;
14 use Template;
15
16 use C4::SIP::ILS::Transaction;
17 use C4::SIP::Sip qw(add_field);
18
19 use C4::Biblio;
20 use C4::Circulation;
21 use C4::Context;
22 use C4::Debug;
23 use C4::Items;
24 use C4::Members;
25 use C4::Reserves;
26 use Koha::Biblios;
27 use Koha::Checkouts::ReturnClaims;
28 use Koha::Checkouts;
29 use Koha::Database;
30 use Koha::DateUtils;
31 use Koha::Holds;
32 use Koha::Items;
33 use Koha::Patrons;
34
35 =encoding UTF-8
36
37 =head1 EXAMPLE
38
39  our %item_db = (
40     '1565921879' => {
41         title => "Perl 5 desktop reference",
42         id => '1565921879',
43         sip_media_type => '001',
44         magnetic_media => 0,
45         hold_queue => [],
46     },
47     '0440242746' => {
48         title => "The deep blue alibi",
49         id => '0440242746',
50         sip_media_type => '001',
51         magnetic_media => 0,
52         hold_queue => [
53             {
54             itemnumber => '823',
55             priority => '1',
56             reservenotes => undef,
57             reservedate => '2008-10-09',
58             found => undef,
59             rtimestamp => '2008-10-09 11:15:06',
60             biblionumber => '406',
61             borrowernumber => '756',
62             branchcode => 'CPL'
63             }
64         ],
65     },
66     '660' => {
67         title => "Harry Potter y el cáliz de fuego",
68         id => '660',
69         sip_media_type => '001',
70         magnetic_media => 0,
71         hold_queue => [],
72     },
73 );
74
75 =cut
76
77 sub new {
78     my ($class, $item_id) = @_;
79     my $type = ref($class) || $class;
80     my $item = Koha::Items->find( { barcode => barcodedecode( $item_id ) } );
81     unless ( $item ) {
82         siplog("LOG_DEBUG", "new ILS::Item('%s'): not found", $item_id);
83         warn "new ILS::Item($item_id) : No item '$item_id'.";
84         return;
85     }
86     my $self = $item->unblessed;
87     $self->{_object}            = $item;
88     $self->{id}                 = $item->barcode; # to SIP, the barcode IS the id.
89     $self->{permanent_location} = $item->homebranch;
90     $self->{collection_code}    = $item->ccode;
91     $self->{call_number}        = $item->itemcallnumber;
92
93     $self->{object} = $item;
94
95     my $it = $item->effective_itemtype;
96     my $itemtype = Koha::Database->new()->schema()->resultset('Itemtype')->find( $it );
97     $self->{sip_media_type} = $itemtype->sip_media_type() if $itemtype;
98
99     # check if its on issue and if so get the borrower
100     my $issue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } );
101     if ($issue) {
102         $self->{due_date} = dt_from_string( $issue->date_due, 'sql' )->truncate( to => 'minute' );
103         my $patron = Koha::Patrons->find( $issue->borrowernumber );
104         $self->{borrowernumber} = $patron->borrowernumber;
105     }
106     my $biblio = Koha::Biblios->find( $self->{biblionumber} );
107     my $holds = $biblio->current_holds->unblessed;
108     $self->{hold_queue} = $holds;
109     $self->{hold_shelf}    = [( grep {   defined $_->{found}  and $_->{found} eq 'W' } @{$self->{hold_queue}} )];
110     $self->{pending_queue} = [( grep {(! defined $_->{found}) or  $_->{found} ne 'W' } @{$self->{hold_queue}} )];
111     $self->{title} = $biblio->title;
112     $self->{author} = $biblio->author;
113     bless $self, $type;
114
115     siplog( "LOG_DEBUG", "new ILS::Item('%s'): found with title '%s'",
116         $item_id, $self->{title} // '' );
117
118     return $self;
119 }
120
121 # 0 means read-only
122 # 1 means read/write
123
124 my %fields = (
125     id                  => 0,
126     sip_media_type      => 0,
127     sip_item_properties => 0,
128     magnetic_media      => 0,
129     permanent_location  => 0,
130     current_location    => 0,
131     print_line          => 1,
132     screen_msg          => 1,
133     itemnumber          => 0,
134     biblionumber        => 0,
135     barcode             => 0,
136     onloan              => 0,
137     collection_code     => 0,
138     call_number         => 0,
139     enumchron           => 0,
140     location            => 0,
141     author              => 0,
142     title               => 0,
143 );
144
145 sub next_hold {
146     my $self = shift;
147     # use Data::Dumper; warn "next_hold() hold_shelf: " . Dumper($self->{hold_shelf}); warn "next_hold() pending_queue: " . $self->{pending_queue};
148     foreach (@{$self->hold_shelf}) {    # If this item was taken from the hold shelf, then that reserve still governs
149         next unless ($_->{itemnumber} and $_->{itemnumber} == $self->{itemnumber});
150         return $_;
151     }
152     if (scalar @{$self->{pending_queue}}) {    # Otherwise, if there is at least one hold, the first (best priority) gets it
153         return  $self->{pending_queue}->[0];
154     }
155     return;
156 }
157
158 # hold_patron_id is NOT the barcode.  It's the borrowernumber.
159 # If a return triggers capture for a hold the borrowernumber is passed
160 # and saved so that other hold info can be retrieved
161 sub hold_patron_id {
162     my $self = shift;
163     my $id   = shift;
164     if ($id) {
165         $self->{hold}->{borrowernumber} = $id;
166     }
167     if ($self->{hold} ) {
168         return $self->{hold}->{borrowernumber};
169     }
170     return;
171
172 }
173 sub hold_patron_name {
174     my ( $self, $template ) = @_;
175     my $borrowernumber = $self->hold_patron_id() or return q{};
176
177     if ($template) {
178         my $tt = Template->new();
179
180         my $patron = Koha::Patrons->find($borrowernumber);
181
182         my $output;
183         $tt->process( \$template, { patron => $patron }, \$output );
184         return $output;
185     }
186
187     my $holder = Koha::Patrons->find( $borrowernumber );
188     unless ($holder) {
189         siplog("LOG_ERR", "While checking hold, failed to retrieve the patron with borrowernumber '$borrowernumber'");
190         return q{};
191     }
192     my $email = $holder->email || '';
193     my $phone = $holder->phone || '';
194     my $extra = ($email and $phone) ? " ($email, $phone)" :  # both populated, employ comma
195                 ($email or  $phone) ? " ($email$phone)"   :  # only 1 populated, we don't care which: no comma
196                 "" ;                                         # neither populated, empty string
197     my $name = $holder->firstname ? $holder->firstname . ' ' : '';
198     $name .= $holder->surname . $extra;
199     return $name;
200 }
201
202 sub hold_patron_bcode {
203     my $self = shift;
204     my $borrowernumber = (@_ ? shift: $self->hold_patron_id()) or return q{};
205     my $holder = Koha::Patrons->find( $borrowernumber );
206     if ($holder and $holder->cardnumber ) {
207         return $holder->cardnumber;
208     }
209     return q();
210 }
211
212 sub destination_loc {
213     my $self = shift;
214     my $set_loc = shift;
215     if ($set_loc) {
216         $self->{dest_loc} = $set_loc;
217     }
218     if ($self->{dest_loc} ) {
219         return $self->{dest_loc};
220     }
221     return q{};
222 }
223
224 our $AUTOLOAD;
225
226 sub DESTROY { } # keeps AUTOLOAD from catching inherent DESTROY calls
227
228 sub AUTOLOAD {
229     my $self = shift;
230     my $class = ref($self) or croak "$self is not an object";
231     my $name = $AUTOLOAD;
232
233     $name =~ s/.*://;
234
235     unless (exists $fields{$name}) {
236                 croak "Cannot access '$name' field of class '$class'";
237     }
238
239         if (@_) {
240         $fields{$name} or croak "Field '$name' of class '$class' is READ ONLY.";
241                 return $self->{$name} = shift;
242         } else {
243                 return $self->{$name};
244         }
245 }
246
247 sub status_update {     # FIXME: this looks unimplemented
248     my ($self, $props) = @_;
249     my $status = C4::SIP::ILS::Transaction->new();
250     $self->{sip_item_properties} = $props;
251     $status->{ok} = 1;
252     return $status;
253 }
254
255 sub title_id {
256     my $self = shift;
257     return $self->{title};
258 }
259
260 sub sip_circulation_status {
261     my $self = shift;
262     if ( $self->{_object}->get_transfer ) {
263         return '10'; # in transit between libraries
264     }
265     elsif ( Koha::Checkouts::ReturnClaims->search({ itemnumber => $self->{_object}->id, resolution => undef })->count ) {
266         return '11';    # claimed returned
267     }
268     elsif ( $self->{itemlost} ) {
269         return '12';    # lost
270     }
271     elsif ( $self->{borrowernumber} ) {
272         return '04';    # charged
273     }
274     elsif ( grep { $_->{itemnumber} == $self->{itemnumber}  } @{ $self->{hold_shelf} } ) {
275         return '08';    # waiting on hold shelf
276     }
277     else {
278         return '03';    # available
279     }    # FIXME: 01-13 enumerated in spec.
280 }
281
282 sub sip_security_marker {
283     my $self = shift;
284     return '02';        # FIXME? 00-other; 01-None; 02-Tattle-Tape Security Strip (3M); 03-Whisper Tape (3M)
285 }
286 sub sip_fee_type {
287     my $self = shift;
288     return '01';    # FIXME? 01-09 enumerated in spec.  We just use O1-other/unknown.
289 }
290
291 sub fee {
292     my $self = shift;
293     return $self->{fee} || 0;
294 }
295 sub fee_currency {
296     my $self = shift;
297     return $self->{currency} || 'USD';
298 }
299 sub owner {
300     my $self = shift;
301     return $self->{homebranch};
302 }
303 sub hold_queue {
304     my $self = shift;
305         (defined $self->{hold_queue}) or return [];
306     return $self->{hold_queue};
307 }
308 sub pending_queue {
309     my $self = shift;
310         (defined $self->{pending_queue}) or return [];
311     return $self->{pending_queue};
312 }
313 sub hold_shelf {
314     my $self = shift;
315         (defined $self->{hold_shelf}) or return [];
316     return $self->{hold_shelf};
317 }
318
319 sub hold_queue_position {
320         my ($self, $patron_id) = @_;
321         ($self->{hold_queue}) or return 0;
322         my $i = 0;
323         foreach (@{$self->{hold_queue}}) {
324                 $i++;
325                 $_->{patron_id} or next;
326                 if ($self->barcode_is_borrowernumber($patron_id, $_->{borrowernumber})) {
327                         return $i;  # maybe should return $_->{priority}
328                 }
329         }
330     return 0;
331 }
332
333 sub due_date {
334     my $self = shift;
335     return $self->{due_date} || 0;
336 }
337 sub recall_date {
338     my $self = shift;
339     return $self->{recall_date} || 0;
340 }
341 sub hold_pickup_date {
342     my $self = shift;
343
344     my $hold = Koha::Holds->find({ itemnumber => $self->{itemnumber}, found => 'W' });
345     if ( $hold ) {
346         return $hold->expirationdate || 0;
347     }
348
349     return 0;
350 }
351
352 # This is a partial check of "availability".  It is not supposed to check everything here.
353 # An item is available for a patron if it is:
354 # 1) checked out to the same patron 
355 #    AND no pending (i.e. non-W) hold queue
356 # OR
357 # 2) not checked out
358 #    AND (not on hold_shelf OR is on hold_shelf for patron)
359 #
360 # What this means is we are consciously allowing the patron to checkout (but not renew) an item that DOES
361 # have non-W holds on it, but has not been "picked" from the stacks.  That is to say, the
362 # patron has retrieved the item before the librarian.
363 #
364 # We don't check if the patron is at the front of the pending queue in the first case, because
365 # they should not be able to place a hold on an item they already have.
366
367 sub available {
368         my ($self, $for_patron) = @_;
369         my $count  = (defined $self->{pending_queue}) ? scalar @{$self->{pending_queue}} : 0;
370         my $count2 = (defined $self->{hold_shelf}   ) ? scalar @{$self->{hold_shelf}   } : 0;
371         $debug and print STDERR "availability check: pending_queue size $count, hold_shelf size $count2\n";
372     if (defined($self->{borrowernumber})) {
373         ($self->{borrowernumber} eq $for_patron) or return 0;
374                 return ($count ? 0 : 1);
375         } else {        # not checked out
376         ($count2) and return $self->barcode_is_borrowernumber($for_patron, $self->{hold_shelf}[0]->{borrowernumber});
377         }
378         return 0;
379 }
380
381 sub _barcode_to_borrowernumber {
382     my $known = shift;
383     return unless defined $known;
384     my $patron = Koha::Patrons->find( { cardnumber => $known } ) or return;
385     return $patron->borrowernumber
386 }
387 sub barcode_is_borrowernumber {    # because hold_queue only has borrowernumber...
388     my $self = shift;
389     my $barcode = shift;
390     my $number  = shift or return;    # can't be zero
391     return unless defined $barcode; # might be 0 or 000 or 000000
392     my $converted = _barcode_to_borrowernumber($barcode);
393     return unless $converted;
394     return ($number == $converted);
395 }
396 sub fill_reserve {
397     my $self = shift;
398     my $hold = shift or return;
399     foreach (qw(biblionumber borrowernumber reservedate)) {
400         $hold->{$_} or return;
401     }
402     return ModReserveFill($hold);
403 }
404
405 =head2 build_additional_item_fields_string
406
407 This method builds the part of the sip message for additional item fields
408 to send in the item related message responses
409
410 =cut
411
412 sub build_additional_item_fields_string {
413     my ( $self, $server ) = @_;
414
415     my $string = q{};
416
417     if ( $server->{account}->{item_field} ) {
418         my @fields_to_send =
419           ref $server->{account}->{item_field} eq "ARRAY"
420           ? @{ $server->{account}->{item_field} }
421           : ( $server->{account}->{item_field} );
422
423         foreach my $f ( @fields_to_send ) {
424             my $code = $f->{code};
425             my $value = $self->{object}->$code;
426             $string .= add_field( $f->{field}, $value );
427         }
428     }
429
430     return $string;
431 }
432
433 1;
434 __END__
435