]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Utils/MFHD.pm
retarget title holds after transfering to a new bib
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Utils / MFHD.pm
1 package MFHD;
2 use strict;
3 use warnings;
4 use integer;
5 use Carp;
6 use DateTime::Format::Strptime;
7 use Data::Dumper;
8
9 # for inherited methods to work properly, we need to force a
10 # MARC::Record version greater than 2.0.0
11 use MARC::Record "2.0.1";
12 use base 'MARC::Record';
13
14 use OpenILS::Utils::MFHD::Caption;
15 use OpenILS::Utils::MFHD::Holding;
16
17 sub new {
18     my $proto = shift;
19     my $class = ref($proto) || $proto;
20     my $self  = shift;
21
22     $self->{_strp_date} = new DateTime::Format::Strptime(pattern => '%F');
23
24     $self->{_mfhd_CAPTIONS} = {};
25     $self->{_mfhd_COMPRESSIBLE} = (substr($self->leader, 17, 1) =~ /[45]/);
26
27     foreach my $field ('853', '854', '855') {
28         my $captions = {};
29         foreach my $caption ($self->field($field)) {
30             my $cap_id;
31
32             $cap_id = $caption->subfield('8') || '0';
33
34             if (exists $captions->{$cap_id}) {
35                 carp "Multiple MFHD captions with label '$cap_id'";
36             }
37
38             $captions->{$cap_id} = new MFHD::Caption($caption);
39             if ($self->{_mfhd_COMPRESSIBLE}) {
40                 $self->{_mfhd_COMPRESSIBLE} &&=
41                   $captions->{$cap_id}->compressible;
42             }
43         }
44         $self->{_mfhd_CAPTIONS}->{$field} = $captions;
45     }
46
47     foreach my $field ('863', '864', '865') {
48         my $holdings = {};
49         my $cap_field;
50
51         ($cap_field = $field) =~ s/6/5/;
52
53         foreach my $hfield ($self->field($field)) {
54             my ($linkage, $link_id, $seqno);
55             my $holding;
56
57             $linkage = $hfield->subfield('8');
58             ($link_id, $seqno) = split(/\./, $linkage);
59
60             if (!exists $holdings->{$link_id}) {
61                 $holdings->{$link_id} = {};
62             }
63             $holding =
64               new MFHD::Holding($seqno, $hfield,
65                 $self->{_mfhd_CAPTIONS}->{$cap_field}->{$link_id});
66             $holdings->{$link_id}->{$seqno} = $holding;
67
68             if ($self->{_mfhd_COMPRESSIBLE}) {
69                 $self->{_mfhd_COMPRESSIBLE} &&= $holding->validate;
70             }
71         }
72         $self->{_mfhd_HOLDINGS}->{$field} = $holdings;
73     }
74
75     bless($self, $class);
76     return $self;
77 }
78
79 sub compressible {
80     my $self = shift;
81
82     return $self->{_mfhd_COMPRESSIBLE};
83 }
84
85 sub caption_link_ids {
86     my $self  = shift;
87     my $field = shift;
88
89     return sort keys %{$self->{_mfhd_CAPTIONS}->{$field}};
90 }
91
92 # optional argument to get back a 'hashref' or an 'array' (default)
93 sub captions {
94     my $self  = shift;
95     my $tag = shift;
96     my $return_type = shift;
97
98     # TODO: add support for caption types as argument? (base, index, supplement)
99     my @sorted_ids = $self->caption_link_ids($tag);
100
101     if (defined($return_type) and $return_type eq 'hashref') {
102         my %captions;
103         foreach my $link_id (@sorted_ids) {
104             $captions{$link_id} = $self->{_mfhd_CAPTIONS}{$tag}{$link_id};
105         }
106         return \%captions;
107     } else {
108         my @captions;
109         foreach my $link_id (@sorted_ids) {
110             push(@captions, $self->{_mfhd_CAPTIONS}{$tag}{$link_id});
111         }
112         return @captions;
113     }
114 }
115
116 sub append_fields {
117     my $self = shift;
118
119     my $field_count = $self->SUPER::append_fields(@_);
120     if ($field_count) {
121         foreach my $field (@_) {
122             $self->_avoid_link_collision($field);
123             my $field_type = ref $field;
124             if ($field_type eq 'MFHD::Holding') {
125                 $self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$field->seqno} = $field;
126             } elsif ($field_type eq 'MFHD::Caption') {
127                 $self->{_mfhd_CAPTIONS}{$field->tag}{$field->link_id} = $field;
128             }
129         }
130         return $field_count;
131     } else {
132         return;
133     }   
134 }
135
136 sub delete_field {
137     my $self = shift;
138     my $field = shift;
139
140     my $field_count = $self->SUPER::delete_field($field);
141     if ($field_count) {
142         my $field_type = ref($field);
143         if ($field_type eq 'MFHD::Holding') {
144             delete($self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$field->seqno});
145         } elsif ($field_type eq 'MFHD::Caption') {
146             delete($self->{_mfhd_CAPTIONS}{$field->tag}{$field->link_id});
147         }
148         return $field_count;
149     } else {
150         return;
151     }
152 }
153
154 sub insert_fields_before {
155     my $self = shift;
156     my $before = shift;
157
158     my $field_count = $self->SUPER::insert_fields_before($before, @_);
159     if ($field_count) {
160         foreach my $field (@_) {
161             $self->_avoid_link_collision($field);
162             my $field_type = ref $field;
163             if ($field_type eq 'MFHD::Holding') {
164                 $self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$field->seqno} = $field;
165             } elsif ($field_type eq 'MFHD::Caption') {
166                 $self->{_mfhd_CAPTIONS}{$field->tag}{$field->link_id} = $field;
167             }
168         }
169         return $field_count;
170     } else {
171         return;
172     }
173 }
174
175 sub insert_fields_after {
176     my $self = shift;
177     my $after = shift;
178
179     my $field_count = $self->SUPER::insert_fields_after($after, @_);
180     if ($field_count) {
181         foreach my $field (@_) {
182             $self->_avoid_link_collision($field);
183             my $field_type = ref $field;
184             if ($field_type eq 'MFHD::Holding') {
185                 $self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$field->seqno} = $field;
186             } elsif ($field_type eq 'MFHD::Caption') {
187                 $self->{_mfhd_CAPTIONS}{$field->tag}{$field->link_id} = $field;
188             }
189         }
190         return $field_count;
191     } else {
192         return;
193     }
194 }
195
196 sub _avoid_link_collision {
197     my $self = shift;
198     my $field = shift;
199
200     my $fieldref = ref($field);
201     if ($fieldref eq 'MFHD::Holding') {
202         my $seqno = $field->seqno;
203         my $changed_seqno = 0;
204         if (exists($self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$seqno})) {
205             $changed_seqno = 1;
206             do {
207                 $seqno++;
208             } while (exists($self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$seqno}));
209         }
210         $field->seqno($seqno) if $changed_seqno;
211     } elsif ($fieldref eq 'MFHD::Caption') {
212         my $link_id = $field->link_id;
213         my $changed_link_id = 0;
214         if (exists($self->{_mfhd_CAPTIONS}{$field->tag}{$link_id})) {
215             $link_id++;
216             $changed_link_id = 1;
217             do {
218                 $link_id++;
219             } while (exists($self->{_mfhd_CAPTIONS}{$field->tag}{$link_id}));
220         }
221         $field->link_id($link_id) if $changed_link_id;
222     }
223 }
224
225 sub active_captions {
226     my $self  = shift;
227     my $tag = shift;
228
229     # TODO: add support for caption types as argument? (basic, index, supplement)
230     my @captions;
231     my @active_captions;
232
233     @captions = $self->captions($tag);
234
235     # TODO: for now, we will assume the last 85X field is active
236     # and the rest are historical.  The standard is hazy about
237     # how multiple active patterns of the same 85X type should be
238     # handled.  We will, however, return as an array for future
239     # use.
240     push(@active_captions, $captions[-1]);
241
242     return @active_captions;
243 }
244
245 sub holdings {
246     my $self  = shift;
247     my $field = shift;
248     my $capid = shift;
249
250     return
251       sort { $a->seqno <=> $b->seqno }
252       values %{$self->{_mfhd_HOLDINGS}->{$field}->{$capid}};
253 }
254
255 sub _holding_date {
256     my $self = shift;
257     my $holding = shift;
258
259     return $self->{_strp_date}->parse_datetime($holding->chron_to_date);
260 }
261
262 #
263 # generate_predictions()
264 # Accepts a hash ref of options initially defined as:
265 # base_holding : reference to the holding field to predict from
266 # num_to_predict : the number of issues you wish to predict
267 # OR
268 # end_holding : holding field ref, keep predicting until you meet or exceed it
269 # OR
270 # end_date : keep predicting until you exceed this
271 #
272 # The basic method is to first convert to a single holding if compressed, then
273 # increment the holding and save the resulting values to @predictions.
274
275 # returns @predictions, an array of holding field refs (including end_holding
276 # if applicable but NOT base_holding)
277
278 sub generate_predictions {
279     my ($self, $options) = @_;
280
281     my $base_holding   = $options->{base_holding};
282     my $num_to_predict = $options->{num_to_predict};
283     my $end_holding    = $options->{end_holding};
284     my $end_date       = $options->{end_date};
285     my $max_to_predict = $options->{max_to_predict} || 10000; # fail-safe
286
287     if (!defined($base_holding)) {
288         carp("Base holding not defined in generate_predictions, returning empty set");
289         return ();
290     }
291     if ($base_holding->is_compressed) {
292         carp("Ambiguous compressed base holding in generate_predictions, returning empty set");
293         return ();
294     }
295     my $curr_holding = $base_holding->clone; # prevent side-effects
296     
297     my @predictions;
298         
299     if ($num_to_predict) {
300         for (my $i = 0; $i < $num_to_predict; $i++) {
301             push(@predictions, $curr_holding->increment->clone);
302         }
303     } elsif (defined($end_holding)) {
304         $end_holding = $end_holding->clone; # prevent side-effects
305         my $next_holding = $curr_holding->increment->clone;
306         my $num_predicted = 0;
307         while ($next_holding le $end_holding) {
308             push(@predictions, $next_holding);
309             $num_predicted++;
310             if ($num_predicted >= $max_to_predict) {
311                 carp("Maximum prediction count exceeded");
312                 last;
313             }
314             $next_holding = $curr_holding->increment->clone;
315         }
316     } elsif (defined($end_date)) {
317         my $next_holding = $curr_holding->increment->clone;
318         my $num_predicted = 0;
319         while ($self->_holding_date($next_holding) <= $end_date) {
320             push(@predictions, $next_holding);
321             $num_predicted++;
322             if ($num_predicted >= $max_to_predict) {
323                 carp("Maximum prediction count exceeded");
324                 last;
325             }
326             $next_holding = $curr_holding->increment->clone;
327         }
328     }
329
330     return @predictions;
331 }
332
333 #
334 # create an array of compressed holdings from all holdings for a given caption,
335 # compressing as needed
336 #
337 # Optionally you can skip sorting, but the resulting compression will be compromised
338 # if the current holdings are out of order
339 #
340 # TODO: gap marking, gap preservation
341 #
342 # TODO: some of this could be moved to the Caption object to allow for 
343 # decompression in the absense of an overarching MFHD object
344 #
345 sub get_compressed_holdings {
346     my $self = shift;
347     my $caption = shift;
348     my $opts = shift;
349     my $skip_sort = $opts->{'skip_sort'};
350
351     # make sure none are compressed
352     my @decomp_holdings;
353     if ($skip_sort) {
354         @decomp_holdings = $self->get_decompressed_holdings($caption, {'skip_sort' => 1});
355     } else {
356         # sort for best algorithm
357         @decomp_holdings = $self->get_decompressed_holdings($caption, {'dedupe' => 1});
358     }
359
360     return () if !@decomp_holdings;
361
362     my $runner = $decomp_holdings[0]->clone->increment;   
363     my $curr_holding = shift(@decomp_holdings);
364     $curr_holding = $curr_holding->clone;
365     my $seqno = 1;
366     $curr_holding->seqno($seqno);
367     my @comp_holdings;
368 #    my $last_holding;
369     foreach my $holding (@decomp_holdings) {
370         if ($runner eq $holding) {
371             $curr_holding->extend;
372             $runner->increment;
373 #        } elsif ($holding eq $last_holding) {
374 #            carp("Found duplicate holding in compression set, skipping");
375         } elsif ($runner gt $holding) { # should not happen unless holding is not in series
376             carp("Found unexpected holding, skipping");
377         } else {
378             push(@comp_holdings, $curr_holding);
379             while ($runner le $holding) {
380                 $runner->increment;
381             }
382             $curr_holding = $holding->clone;
383             $seqno++;
384             $curr_holding->seqno($seqno);
385         }
386 #        $last_holding = $holding;
387     }
388     push(@comp_holdings, $curr_holding);
389
390     return @comp_holdings;
391 }
392
393 #
394 # create an array of single holdings from all holdings for a given caption,
395 # decompressing as needed
396 #
397 # resulting array is returned as they come in the record, unsorted
398 #
399 # optional argument will reorder and renumber the holdings before returning
400
401 # TODO: some of this could be moved to the Caption (and/or Holding) object to
402 # allow for decompression in the absense of an overarching MFHD object
403 #
404 sub get_decompressed_holdings {
405     my $self = shift;
406     my $caption = shift;
407     my $opts = shift;
408     my $skip_sort = $opts->{'skip_sort'};
409     my $dedupe = $opts->{'dedupe'};
410
411     if ($dedupe and $skip_sort) {
412         carp("Attempted deduplication without sorting, failure likely");
413     }
414
415     my $htag    = $caption->tag;
416     my $link_id = $caption->link_id;
417     $htag =~ s/^85/86/;
418     my @holdings = $self->holdings($htag, $link_id);
419
420     return () if !@holdings;
421
422     my @decomp_holdings;
423
424     foreach my $holding (@holdings) {
425         if (!$holding->is_compressed) {
426             push(@decomp_holdings, $holding->clone);
427         } else {
428             my $base_holding = $holding->clone->compressed_to_first;
429             my @new_holdings = $self->generate_predictions(
430                 {'base_holding' => $base_holding,
431                  'end_holding' => $holding->clone->compressed_to_last});
432             push(@decomp_holdings, $base_holding, @new_holdings);
433         }
434     }
435
436     unless ($skip_sort) {
437         my @temp_holdings = sort {$a cmp $b} @decomp_holdings;
438         @decomp_holdings = @temp_holdings;
439     }
440
441     my @return_holdings = (shift(@decomp_holdings));
442     $return_holdings[0]->seqno(1);
443     my $seqno = 2;
444     foreach my $holding (@decomp_holdings) { # renumber sequence
445         if ($holding eq $return_holdings[-1] and $dedupe) {
446             carp("Found duplicate holding in decompression set, discarding");
447             next;
448         }
449         $holding->seqno($seqno);
450         $seqno++;
451         push(@return_holdings, $holding);
452     }
453
454     return @return_holdings;
455 }
456
457 #
458 # format_holdings(): Generate textual display of all holdings in record
459 # for given type of caption (853--855) taking into account all the
460 # captions, holdings statements, and textual
461 # holdings.
462 #
463 # returns string formatted holdings as one very long line.
464 # Caller must provide any label (such as "library has:" and insert
465 # line breaks as appropriate.
466
467 # Translate caption field labels to the corresponding textual holdings
468 # statement labels. That is, convert 853 "Basic bib unit" caption to
469 # 866 "basic bib unit" text holdings label.
470
471 my %cap_to_txt = (
472                   '853' => '866',
473                   '854' => '867',
474                   '855' => '868',
475                  );
476
477 sub format_holdings {
478     my $self = shift;
479     my $field = shift;
480     my $holdings_field;
481     my @txt_holdings;
482     my %txt_link_ids;
483     my $holdings_stmt = '';
484     my ($l, $start);
485
486     # convert caption field id to holdings field id
487     ($holdings_field = $field) =~ s/5/6/;
488
489     # Textual holdings statements complicate the basic algorithm for
490     # formatting the holdings: If there's a textual holdings statement
491     # with the subfield "$80", then that overrides ALL the MFHD holdings
492     # information and is all that is displayed. Otherwise, the textual
493     # holdings statements will either replace some of the MFHD holdings
494     # information, or supplement it, depending on the value of the
495     # $8 linkage subfield.
496
497     if (defined $self->field($cap_to_txt{$field})) {
498         @txt_holdings = $self->field($cap_to_txt{$field});
499
500         foreach my $txt (@txt_holdings) {
501
502             # if there's a $80 subfield, then we're done, it's
503             # all the formatted holdings
504             if ($txt->subfield('8') eq '0') {
505                 # textual holdings statement that completely
506                 # replaces MFHD holdings in 853/863, etc.
507                 $holdings_stmt = $txt->subfield('a');
508
509                 if (defined $txt->subfield('z')) {
510                     $holdings_stmt .= ' -- ' . $txt->subfield('z');
511                 }
512
513                 printf("# format_holdings() returning %s txt holdings\n",
514                        $cap_to_txt{$field});
515                 return $holdings_stmt;
516             }
517
518             # If there are non-$80 subfields in the textual holdings
519             # then we need to keep track of the subfields, so we can
520             # intersperse the textual holdings in with the the calculated
521             # holdings from the 853/863 fields.
522             foreach my $linkid ($txt->subfield('8')) {
523                 $txt_link_ids{$linkid} = $txt;
524             }
525         }
526     }
527
528     # Now loop through all the captions, finding the corresponding
529     # holdings statements (either MFHD or textual), and build up the
530     # complete formatted holdings statement. The textual holdings statements
531     # have either the same link id field as a caption, which means that
532     # the text holdings win, or they have ids that are interfiled with
533     # the captions, which mean they go into the middle.
534
535     my @ids = sort($self->caption_link_ids($field), keys %txt_link_ids);
536     foreach my $cap_id (@ids) {
537         my $last_txt = undef;
538
539         if (exists $txt_link_ids{$cap_id}) {
540             # there's a textual holding statement with this caption ID,
541             # so just use that. This covers both the "replaces" and
542             # the "supplements" holdings information options.
543
544             # a single textual holdings statement can replace multiple
545             # captions. If the _last_ caption we saw had a textual
546             # holdings statement, and this caption has the same one, then
547             # we don't add the holdings again.
548             if (!defined $last_txt || ($last_txt != $txt_link_ids{$cap_id})) {
549                 my $txt = $txt_link_ids{$cap_id};
550                 $holdings_stmt .= ',' if $holdings_stmt;
551                 $holdings_stmt .= $txt->subfield('a');
552                 if (defined $txt->subfield('z')) {
553                     $holdings_stmt .= ' -- ' . $txt->subfield('z');
554                 }
555
556                 $last_txt = $txt;
557             }
558             next;
559         }
560
561         # We found a caption that doesn't have a corresponding textual
562         # holdings statement, so reset $last_txt to undef.
563         $last_txt = undef;
564
565         my @holdings = $self->holdings($holdings_field, $cap_id);
566
567         next unless scalar @holdings;
568
569         # XXX Need to format compressed holdings. see code in test.pl
570         # for example. Try to do it without indexing?
571         $holdings_stmt .= ',' if $holdings_stmt;
572
573         if ($self->compressible) {
574             $start = $l = shift @holdings;
575             $holdings_stmt .= $l->format;
576
577             while (my $h = shift @holdings) {
578                 if (!$h->matches($l->next)) {
579                     # this item is not part of the current run,
580                     # close out the run and record this item
581                     if ($l != $start) {
582                         $holdings_stmt .= '-' . $l->format;
583                     }
584
585                     $holdings_stmt .= ',' . $h->format;
586                     $start = $h
587                 } elsif (!scalar(@holdings) || defined($h->subfield('z'))) {
588                     # This is the end of the holdings for this caption
589                     # or this item has a public note that we want
590                     # to display
591                     $holdings_stmt .= '-' . $h->format;
592                 }
593
594                 if (defined $h->subfield('z')) {
595                     $holdings_stmt .= ' -- ' . $h->subfield('z');
596                 }
597
598                 $l = $h;
599             }
600         } else {
601             $holdings_stmt .= ',' if $holdings_stmt;
602             $holdings_stmt .= (shift @holdings)->format;
603             foreach my $h (@holdings) {
604                 $holdings_stmt .= ',' . $h->format;
605                 if (defined $h->subfield('z')) {
606                     $holdings_stmt .= ' -- ' . $h->subfield('z');
607                 }
608             }
609         }
610     }
611
612     return $holdings_stmt;
613 }
614
615 1;