6 use DateTime::Format::Strptime;
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';
14 use OpenILS::Utils::MFHD::Caption;
15 use OpenILS::Utils::MFHD::Holding;
19 my $class = ref($proto) || $proto;
22 $self->{_strp_date} = new DateTime::Format::Strptime(pattern => '%F');
24 $self->{_mfhd_CAPTIONS} = {};
25 $self->{_mfhd_COMPRESSIBLE} = (substr($self->leader, 17, 1) =~ /[45]/);
27 foreach my $field ('853', '854', '855') {
29 foreach my $caption ($self->field($field)) {
32 $cap_id = $caption->subfield('8') || '0';
34 if (exists $captions->{$cap_id}) {
35 carp "Multiple MFHD captions with label '$cap_id'";
38 $captions->{$cap_id} = new MFHD::Caption($caption);
39 if ($self->{_mfhd_COMPRESSIBLE}) {
40 $self->{_mfhd_COMPRESSIBLE} &&=
41 $captions->{$cap_id}->compressible;
44 $self->{_mfhd_CAPTIONS}->{$field} = $captions;
47 foreach my $field ('863', '864', '865') {
51 ($cap_field = $field) =~ s/6/5/;
53 foreach my $hfield ($self->field($field)) {
54 my ($linkage, $link_id, $seqno);
57 $linkage = $hfield->subfield('8');
58 ($link_id, $seqno) = split(/\./, $linkage);
60 if (!exists $holdings->{$link_id}) {
61 $holdings->{$link_id} = {};
64 new MFHD::Holding($seqno, $hfield,
65 $self->{_mfhd_CAPTIONS}->{$cap_field}->{$link_id});
66 $holdings->{$link_id}->{$seqno} = $holding;
68 if ($self->{_mfhd_COMPRESSIBLE}) {
69 $self->{_mfhd_COMPRESSIBLE} &&= $holding->validate;
72 $self->{_mfhd_HOLDINGS}->{$field} = $holdings;
82 return $self->{_mfhd_COMPRESSIBLE};
85 sub caption_link_ids {
89 return sort keys %{$self->{_mfhd_CAPTIONS}->{$field}};
92 # optional argument to get back a 'hashref' or an 'array' (default)
96 my $return_type = shift;
98 # TODO: add support for caption types as argument? (base, index, supplement)
99 my @sorted_ids = $self->caption_link_ids($tag);
101 if (defined($return_type) and $return_type eq 'hashref') {
103 foreach my $link_id (@sorted_ids) {
104 $captions{$link_id} = $self->{_mfhd_CAPTIONS}{$tag}{$link_id};
109 foreach my $link_id (@sorted_ids) {
110 push(@captions, $self->{_mfhd_CAPTIONS}{$tag}{$link_id});
119 my $field_count = $self->SUPER::append_fields(@_);
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;
140 my $field_count = $self->SUPER::delete_field($field);
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});
154 sub insert_fields_before {
158 my $field_count = $self->SUPER::insert_fields_before($before, @_);
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;
175 sub insert_fields_after {
179 my $field_count = $self->SUPER::insert_fields_after($after, @_);
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;
196 sub _avoid_link_collision {
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})) {
208 } while (exists($self->{_mfhd_HOLDINGS}{$field->tag}{$field->caption->link_id}{$seqno}));
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})) {
216 $changed_link_id = 1;
219 } while (exists($self->{_mfhd_CAPTIONS}{$field->tag}{$link_id}));
221 $field->link_id($link_id) if $changed_link_id;
225 sub active_captions {
229 # TODO: add support for caption types as argument? (basic, index, supplement)
233 @captions = $self->captions($tag);
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
240 push(@active_captions, $captions[-1]);
242 return @active_captions;
251 sort { $a->seqno <=> $b->seqno }
252 values %{$self->{_mfhd_HOLDINGS}->{$field}->{$capid}};
255 sub holdings_by_caption {
259 my $htag = $caption->tag;
260 my $link_id = $caption->link_id;
262 return $self->holdings($htag, $link_id);
269 return $self->{_strp_date}->parse_datetime($holding->chron_to_date);
273 # generate_predictions()
274 # Accepts a hash ref of options initially defined as:
275 # base_holding : reference to the holding field to predict from
276 # num_to_predict : the number of issues you wish to predict
278 # end_holding : holding field ref, keep predicting until you meet or exceed it
280 # end_date : keep predicting until you exceed this
282 # The basic method is to first convert to a single holding if compressed, then
283 # increment the holding and save the resulting values to @predictions.
285 # returns @predictions, an array of holding field refs (including end_holding
286 # if applicable but NOT base_holding)
288 sub generate_predictions {
289 my ($self, $options) = @_;
291 my $base_holding = $options->{base_holding};
292 my $num_to_predict = $options->{num_to_predict};
293 my $end_holding = $options->{end_holding};
294 my $end_date = $options->{end_date};
295 my $max_to_predict = $options->{max_to_predict} || 10000; # fail-safe
297 if (!defined($base_holding)) {
298 carp("Base holding not defined in generate_predictions, returning empty set");
301 if ($base_holding->is_compressed) {
302 carp("Ambiguous compressed base holding in generate_predictions, returning empty set");
305 my $curr_holding = $base_holding->clone; # prevent side-effects
309 if ($num_to_predict) {
310 for (my $i = 0; $i < $num_to_predict; $i++) {
311 push(@predictions, $curr_holding->increment->clone);
313 } elsif (defined($end_holding)) {
314 $end_holding = $end_holding->clone; # prevent side-effects
315 my $next_holding = $curr_holding->increment->clone;
316 my $num_predicted = 0;
317 while ($next_holding le $end_holding) {
318 push(@predictions, $next_holding);
320 if ($num_predicted >= $max_to_predict) {
321 carp("Maximum prediction count exceeded");
324 $next_holding = $curr_holding->increment->clone;
326 } elsif (defined($end_date)) {
327 my $next_holding = $curr_holding->increment->clone;
328 my $num_predicted = 0;
329 while ($self->_holding_date($next_holding) <= $end_date) {
330 push(@predictions, $next_holding);
332 if ($num_predicted >= $max_to_predict) {
333 carp("Maximum prediction count exceeded");
336 $next_holding = $curr_holding->increment->clone;
344 # create an array of compressed holdings from all holdings for a given caption,
345 # compressing as needed
347 # Optionally you can skip sorting, but the resulting compression will be compromised
348 # if the current holdings are out of order
350 # TODO: gap marking, gap preservation
352 # TODO: some of this could be moved to the Caption object to allow for
353 # decompression in the absense of an overarching MFHD object
355 sub get_compressed_holdings {
359 my $skip_sort = $opts->{'skip_sort'};
361 # basic check for necessary pattern information
362 if (!scalar keys %{$caption->pattern}) {
363 carp "Cannot compress without pattern data, returning original holdings";
364 return $self->holdings_by_caption($caption);
367 # make sure none are compressed (except for open-ended)
370 @decomp_holdings = $self->get_decompressed_holdings($caption, {'skip_sort' => 1, 'passthru_open_ended' => 1});
372 # sort for best algorithm
373 @decomp_holdings = $self->get_decompressed_holdings($caption, {'dedupe' => 1, 'passthru_open_ended' => 1});
376 return () if !@decomp_holdings;
378 # if first holding is open-ended, it 'includes' all the rest, so return
379 if ($decomp_holdings[0]->is_open_ended) {
380 return ($decomp_holdings[0]);
383 my $runner = $decomp_holdings[0]->clone->increment;
384 my $curr_holding = shift(@decomp_holdings);
385 $curr_holding = $curr_holding->clone;
387 $curr_holding->seqno($seqno);
389 foreach my $holding (@decomp_holdings) {
390 if ($runner eq $holding) {
391 $curr_holding->extend;
393 } elsif ($holding->is_open_ended) { # special case, as it will always be the last
394 if ($runner ge $holding->clone->compressed_to_first) {
395 $curr_holding->compressed_end();
397 push(@comp_holdings, $curr_holding);
398 $curr_holding = $holding->clone;
400 $curr_holding->seqno($seqno);
403 } elsif ($runner gt $holding) { # should not happen unless holding is not in series
404 carp("Found unexpected holding, skipping");
406 push(@comp_holdings, $curr_holding);
409 (my $runner_dump = $runner->as_formatted) =~ s/\n\s+/*/gm; # logging
411 while ($runner le $holding) {
412 # Infinite loops used to happen here. As written today,
413 # ->increment() cannot be guaranteed to eventually falsify
414 # the condition ($runner le $holding) in certain cases.
418 if (++$loop_count >= 10000) {
419 (my $holding_dump = $holding->as_formatted) =~ s/\n\s+/*/gm;
421 croak "\$runner<$runner_dump> didn't catch up with " .
422 "\$holding<$holding_dump> after 10000 increments";
425 $curr_holding = $holding->clone;
427 $curr_holding->seqno($seqno);
430 push(@comp_holdings, $curr_holding);
432 return @comp_holdings;
436 # create an array of single holdings from all holdings for a given caption,
437 # decompressing as needed
439 # optional arguments:
440 # skip_sort: do not sort the returned holdings
441 # dedupe: remove any duplicate holdings from the set
442 # passthru_open_ended: open-ended compressed holdings cannot be logically
443 # decompressed (they are infinite); if set to true these holdings are passed
444 # thru rather than skipped
445 # TODO: some of this could be moved to the Caption (and/or Holding) object to
446 # allow for decompression in the absense of an overarching MFHD object
448 sub get_decompressed_holdings {
452 my $skip_sort = $opts->{'skip_sort'};
453 my $dedupe = $opts->{'dedupe'};
454 my $passthru_open_ended = $opts->{'passthru_open_ended'};
456 if ($dedupe and $skip_sort) {
457 carp("Attempted deduplication without sorting, failure likely");
460 my @holdings = $self->holdings_by_caption($caption);
462 return () if !@holdings;
466 foreach my $holding (@holdings) {
467 if (!$holding->is_compressed) {
468 push(@decomp_holdings, $holding->clone);
469 } elsif ($holding->is_open_ended) {
470 if ($passthru_open_ended) {
471 push(@decomp_holdings, $holding->clone);
473 carp("Open-ended holdings cannot be decompressed, skipping");
476 my $base_holding = $holding->clone->compressed_to_first;
477 my @new_holdings = $self->generate_predictions(
478 {'base_holding' => $base_holding,
479 'end_holding' => $holding->clone->compressed_to_last});
480 push(@decomp_holdings, $base_holding, @new_holdings);
484 unless ($skip_sort) {
485 my @temp_holdings = sort {$a cmp $b} @decomp_holdings;
486 @decomp_holdings = @temp_holdings;
489 my @return_holdings = (shift(@decomp_holdings));
490 $return_holdings[0]->seqno(1);
492 foreach my $holding (@decomp_holdings) { # renumber sequence
493 if ($holding eq $return_holdings[-1] and $dedupe) {
494 carp("Found duplicate holding in decompression set, discarding");
497 $holding->seqno($seqno);
499 push(@return_holdings, $holding);
502 return @return_holdings;
506 # create an array of compressed holdings from all holdings for a given caption,
507 # combining as needed
509 # NOTE: this sub is similar to, but much less aggressive/strict than
510 # get_compressed_holdings(). Ultimately, get_compressed_holdings() might be
511 # deprecated in favor of this
513 # TODO: gap marking, gap preservation
515 # TODO: some of this could be moved to the Caption (and/or Holding) object to
516 # allow for combining in the absense of an overarching MFHD object
518 sub get_combined_holdings {
522 my @holdings = $self->holdings_by_caption($caption);
523 return () if !@holdings;
525 # basic check for necessary pattern information
526 if (!scalar keys %{$caption->pattern}) {
527 carp "Cannot combine without pattern data, returning original holdings";
531 my @sorted_holdings = sort {$a cmp $b} @holdings;
533 my @combined_holdings = (shift(@sorted_holdings));
535 $combined_holdings[0]->seqno($seqno);
536 foreach my $holding (@sorted_holdings) {
537 # short-circuit: if we hit an open-ended holding,
538 # it 'includes' all the rest, so just exit the loop
539 if ($combined_holdings[-1]->is_open_ended) {
541 } elsif ($holding eq $combined_holdings[-1]) {
545 # at this point, we know that $holding is gt $combined_holdings[-1]
546 # we just need to figure out if they overlap or not
548 # first, get the end (or only) holding of [-1]
549 my $last_holding_end = $combined_holdings[-1]->is_compressed ?
550 $combined_holdings[-1]->clone->compressed_to_last
551 : $combined_holdings[-1]->clone;
553 # next, get the end (or only) holding of the current
554 # holding being considered
556 if ($holding->is_compressed) {
557 $holding_end = $holding->is_open_ended ?
559 : $holding->clone->compressed_to_last;
561 $holding_end = $holding;
564 # next, make sure $holding isn't fully contained
566 if ($holding_end and $holding_end le $last_holding_end) {
570 # now, get the beginning (or only) holding of $holding
571 my $holding_start = $holding->is_compressed ?
572 $holding->clone->compressed_to_first
575 # see if they overlap
576 if ($last_holding_end->increment ge $holding_start) {
577 # they overlap, combine them
578 $combined_holdings[-1]->compressed_end($holding_end);
580 # no overlap, start a new group
581 $holding->seqno(++$seqno);
582 push(@combined_holdings, $holding);
587 return @combined_holdings;
591 ## close any open-ended holdings which are followed by another holding by
594 ## This needs more thought about concerning usability (e.g. should it be a
595 ## mutator?), commenting out for now
596 #sub _get_truncated_holdings {
598 # my $caption = shift;
600 # my @holdings = $self->holdings_by_caption($caption);
602 # return () if !@holdings;
604 # @holdings = sort {$a cmp $b} @holdings;
606 # my $current_open_holding;
607 # my @truncated_holdings;
608 # foreach my $holding (@holdings) {
609 # if ($current_open_holding) {
610 # if ($holding->is_open_ended) {
611 # next; # consecutive open holdings are meaningless, as they are contained by the previous
612 # } elsif ($holding->is_compressed) {
613 # $current_open_holding->compressed_end($holding->compressed_to_last);
615 # $current_open_holding->compressed_end($holding);
617 # push(@truncated_holdings, $current_open_holding);
618 # $current_open_holding = undef;
619 # } elsif ($holding->is_open_ended) {
620 # $current_open_holding = $holding;
622 # push(@truncated_holdings, $holding);
626 # # catch possible open holding at end
627 # push(@truncated_holdings, $current_open_holding) if $current_open_holding;
630 # foreach my $holding (@truncated_holdings) { # renumber sequence
631 # $holding->seqno($seqno);
635 # return @truncated_holdings;
639 # format_holdings(): Generate textual display of all holdings in record
640 # for given type of caption (853--855) taking into account all the
641 # captions, holdings statements, and textual
644 # returns string formatted holdings as one very long line.
645 # Caller must provide any label (such as "library has:" and insert
646 # line breaks as appropriate.
648 # Translate caption field labels to the corresponding textual holdings
649 # statement labels. That is, convert 853 "Basic bib unit" caption to
650 # 866 "basic bib unit" text holdings label.
658 sub format_holdings {
664 my $holdings_stmt = '';
667 # convert caption field id to holdings field id
668 ($holdings_field = $field) =~ s/5/6/;
670 # Textual holdings statements complicate the basic algorithm for
671 # formatting the holdings: If there's a textual holdings statement
672 # with the subfield "$80", then that overrides ALL the MFHD holdings
673 # information and is all that is displayed. Otherwise, the textual
674 # holdings statements will either replace some of the MFHD holdings
675 # information, or supplement it, depending on the value of the
676 # $8 linkage subfield.
678 if (defined $self->field($cap_to_txt{$field})) {
679 @txt_holdings = $self->field($cap_to_txt{$field});
681 foreach my $txt (@txt_holdings) {
683 # if there's a $80 subfield, then we're done, it's
684 # all the formatted holdings
685 if ($txt->subfield('8') eq '0') {
686 # textual holdings statement that completely
687 # replaces MFHD holdings in 853/863, etc.
688 $holdings_stmt = $txt->subfield('a');
690 if (defined $txt->subfield('z')) {
691 $holdings_stmt .= ' -- ' . $txt->subfield('z');
694 printf("# format_holdings() returning %s txt holdings\n",
695 $cap_to_txt{$field});
696 return $holdings_stmt;
699 # If there are non-$80 subfields in the textual holdings
700 # then we need to keep track of the subfields, so we can
701 # intersperse the textual holdings in with the the calculated
702 # holdings from the 853/863 fields.
703 foreach my $linkid ($txt->subfield('8')) {
704 $txt_link_ids{$linkid} = $txt;
709 # Now loop through all the captions, finding the corresponding
710 # holdings statements (either MFHD or textual), and build up the
711 # complete formatted holdings statement. The textual holdings statements
712 # have either the same link id field as a caption, which means that
713 # the text holdings win, or they have ids that are interfiled with
714 # the captions, which mean they go into the middle.
716 my @ids = sort($self->caption_link_ids($field), keys %txt_link_ids);
717 foreach my $cap_id (@ids) {
718 my $last_txt = undef;
720 if (exists $txt_link_ids{$cap_id}) {
721 # there's a textual holding statement with this caption ID,
722 # so just use that. This covers both the "replaces" and
723 # the "supplements" holdings information options.
725 # a single textual holdings statement can replace multiple
726 # captions. If the _last_ caption we saw had a textual
727 # holdings statement, and this caption has the same one, then
728 # we don't add the holdings again.
729 if (!defined $last_txt || ($last_txt != $txt_link_ids{$cap_id})) {
730 my $txt = $txt_link_ids{$cap_id};
731 $holdings_stmt .= ',' if $holdings_stmt;
732 $holdings_stmt .= $txt->subfield('a');
733 if (defined $txt->subfield('z')) {
734 $holdings_stmt .= ' -- ' . $txt->subfield('z');
742 # We found a caption that doesn't have a corresponding textual
743 # holdings statement, so reset $last_txt to undef.
746 my @holdings = $self->holdings($holdings_field, $cap_id);
748 next unless scalar @holdings;
750 # XXX Need to format compressed holdings. see code in test.pl
751 # for example. Try to do it without indexing?
752 $holdings_stmt .= ',' if $holdings_stmt;
754 if ($self->compressible) {
755 $start = $l = shift @holdings;
756 $holdings_stmt .= $l->format;
758 while (my $h = shift @holdings) {
759 if (!$h->matches($l->next)) {
760 # this item is not part of the current run,
761 # close out the run and record this item
763 $holdings_stmt .= '-' . $l->format;
766 $holdings_stmt .= ',' . $h->format;
768 } elsif (!scalar(@holdings) || defined($h->subfield('z'))) {
769 # This is the end of the holdings for this caption
770 # or this item has a public note that we want
772 $holdings_stmt .= '-' . $h->format;
775 if (defined $h->subfield('z')) {
776 $holdings_stmt .= ' -- ' . $h->subfield('z');
782 $holdings_stmt .= ',' if $holdings_stmt;
783 $holdings_stmt .= (shift @holdings)->format;
784 foreach my $h (@holdings) {
785 $holdings_stmt .= ',' . $h->format;
786 if (defined $h->subfield('z')) {
787 $holdings_stmt .= ' -- ' . $h->subfield('z');
793 return $holdings_stmt;