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