]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Vandelay.pm
flesh stat_cat_entries in the call number tree method used by Holdings Maintenance...
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Vandelay.pm
1 package OpenILS::Application::Vandelay;
2 use strict; use warnings;
3 use OpenILS::Application;
4 use base qw/OpenILS::Application/;
5 use Unicode::Normalize;
6 use OpenSRF::EX qw/:try/;
7 use OpenSRF::AppSession;
8 use OpenSRF::Utils::SettingsClient;
9 use OpenSRF::Utils::Cache;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Utils::CStoreEditor qw/:funcs/;
12 use MARC::Batch;
13 use MARC::Record;
14 use MARC::File::XML ( BinaryEncoding => 'UTF-8' );
15 use OpenILS::Utils::Fieldmapper;
16 use Time::HiRes qw(time);
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use MIME::Base64;
19 use OpenILS::Const qw/:const/;
20 use OpenILS::Application::AppUtils;
21 use OpenILS::Application::Cat::BibCommon;
22 use OpenILS::Application::Cat::AuthCommon;
23 use OpenILS::Application::Cat::AssetCommon;
24 my $U = 'OpenILS::Application::AppUtils';
25
26 # A list of LDR/06 values from http://loc.gov/marc
27 my %record_types = (
28         a => 'bib',
29         c => 'bib',
30         d => 'bib',
31         e => 'bib',
32         f => 'bib',
33         g => 'bib',
34         i => 'bib',
35         j => 'bib',
36         k => 'bib',
37         m => 'bib',
38         o => 'bib',
39         p => 'bib',
40         r => 'bib',
41         t => 'bib',
42         u => 'holdings',
43         v => 'holdings',
44         x => 'holdings',
45         y => 'holdings',
46         z => 'auth',
47       ' ' => 'bib',
48 );
49
50 sub initialize {}
51 sub child_init {}
52
53 # --------------------------------------------------------------------------------
54 # Biblio ingest
55
56 sub create_bib_queue {
57     my $self = shift;
58     my $client = shift;
59     my $auth = shift;
60     my $name = shift;
61     my $owner = shift;
62     my $type = shift;
63     my $import_def = shift;
64
65     my $e = new_editor(authtoken => $auth, xact => 1);
66
67     return $e->die_event unless $e->checkauth;
68     return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
69     $owner ||= $e->requestor->id;
70
71     if ($e->search_vandelay_bib_queue( {name => $name, owner => $owner, queue_type => $type})->[0]) {
72         $e->rollback;
73         return OpenILS::Event->new('BIB_QUEUE_EXISTS') 
74     }
75
76     my $queue = new Fieldmapper::vandelay::bib_queue();
77     $queue->name( $name );
78     $queue->owner( $owner );
79     $queue->queue_type( $type ) if ($type);
80     $queue->item_attr_def( $import_def ) if ($import_def);
81
82     my $new_q = $e->create_vandelay_bib_queue( $queue );
83     return $e->die_event unless ($new_q);
84     $e->commit;
85
86     return $new_q;
87 }
88 __PACKAGE__->register_method(  
89     api_name   => "open-ils.vandelay.bib_queue.create",
90     method     => "create_bib_queue",
91     api_level  => 1,
92     argc       => 4,
93 );                      
94
95
96 sub create_auth_queue {
97     my $self = shift;
98     my $client = shift;
99     my $auth = shift;
100     my $name = shift;
101     my $owner = shift;
102     my $type = shift;
103
104     my $e = new_editor(authtoken => $auth, xact => 1);
105
106     return $e->die_event unless $e->checkauth;
107     return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
108     $owner ||= $e->requestor->id;
109
110     if ($e->search_vandelay_bib_queue({name => $name, owner => $owner, queue_type => $type})->[0]) {
111         $e->rollback;
112         return OpenILS::Event->new('AUTH_QUEUE_EXISTS') 
113     }
114
115     my $queue = new Fieldmapper::vandelay::authority_queue();
116     $queue->name( $name );
117     $queue->owner( $owner );
118     $queue->queue_type( $type ) if ($type);
119
120     my $new_q = $e->create_vandelay_authority_queue( $queue );
121     $e->die_event unless ($new_q);
122     $e->commit;
123
124     return $new_q;
125 }
126 __PACKAGE__->register_method(  
127     api_name   => "open-ils.vandelay.authority_queue.create",
128     method     => "create_auth_queue",
129     api_level  => 1,
130     argc       => 3,
131 );                      
132
133 sub add_record_to_bib_queue {
134     my $self = shift;
135     my $client = shift;
136     my $auth = shift;
137     my $queue = shift;
138     my $marc = shift;
139     my $purpose = shift;
140     my $bib_source = shift;
141
142     my $e = new_editor(authtoken => $auth, xact => 1);
143
144     $queue = $e->retrieve_vandelay_bib_queue($queue);
145
146     return $e->die_event unless $e->checkauth;
147     return $e->die_event unless
148         ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
149          $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
150
151     my $new_rec = _add_bib_rec($e, $marc, $queue->id, $purpose, $bib_source);
152
153     return $e->die_event unless ($new_rec);
154     $e->commit;
155     return $new_rec;
156 }
157 __PACKAGE__->register_method(  
158     api_name   => "open-ils.vandelay.queued_bib_record.create",
159     method     => "add_record_to_bib_queue",
160     api_level  => 1,
161     argc       => 3,
162 );                      
163
164 sub _add_bib_rec {
165     my $e = shift;
166     my $marc = shift;
167     my $queue = shift;
168     my $purpose = shift;
169     my $bib_source = shift;
170
171     my $rec = new Fieldmapper::vandelay::queued_bib_record();
172     $rec->marc( $marc );
173     $rec->queue( $queue );
174     $rec->purpose( $purpose ) if ($purpose);
175     $rec->bib_source($bib_source);
176
177     return $e->create_vandelay_queued_bib_record( $rec );
178 }
179
180 sub add_record_to_authority_queue {
181     my $self = shift;
182     my $client = shift;
183     my $auth = shift;
184     my $queue = shift;
185     my $marc = shift;
186     my $purpose = shift;
187
188     my $e = new_editor(authtoken => $auth, xact => 1);
189
190     $queue = $e->retrieve_vandelay_authority_queue($queue);
191
192     return $e->die_event unless $e->checkauth;
193     return $e->die_event unless
194         ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
195          $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
196
197     my $new_rec = _add_auth_rec($e, $marc, $queue->id, $purpose);
198
199     return $e->die_event unless ($new_rec);
200     $e->commit;
201     return $new_rec;
202 }
203 __PACKAGE__->register_method(
204     api_name   => "open-ils.vandelay.queued_authority_record.create",
205     method     => "add_record_to_authority_queue",
206     api_level  => 1,
207     argc       => 3,
208 );
209
210 sub _add_auth_rec {
211     my $e = shift;
212     my $marc = shift;
213     my $queue = shift;
214     my $purpose = shift;
215
216     my $rec = new Fieldmapper::vandelay::queued_authority_record();
217     $rec->marc( $marc );
218     $rec->queue( $queue );
219     $rec->purpose( $purpose ) if ($purpose);
220
221     return $e->create_vandelay_queued_authority_record( $rec );
222 }
223
224 sub process_spool {
225     my $self = shift;
226     my $client = shift;
227     my $auth = shift;
228     my $fingerprint = shift || '';
229     my $queue_id = shift;
230     my $purpose = shift;
231     my $filename = shift;
232     my $bib_source = shift;
233
234     my $e = new_editor(authtoken => $auth, xact => 1);
235     return $e->die_event unless $e->checkauth;
236
237     my $queue;
238     my $type = $self->{record_type};
239
240     if($type eq 'bib') {
241         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
242     } else {
243         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
244     }
245
246     my $evt = check_queue_perms($e, $type, $queue);
247     return $evt if ($evt);
248
249     my $cache = new OpenSRF::Utils::Cache();
250
251     if($fingerprint) {
252         my $data = $cache->get_cache('vandelay_import_spool_' . $fingerprint);
253         $purpose = $data->{purpose};
254         $filename = $data->{path};
255         $bib_source = $data->{bib_source};
256     }
257
258     unless(-r $filename) {
259         $logger->error("unable to read MARC file $filename");
260         return -1; # make this an event XXX
261     }
262
263     $logger->info("vandelay spooling $fingerprint purpose=$purpose file=$filename");
264
265     my $marctype = 'USMARC'; 
266
267     open F, $filename;
268     $marctype = 'XML' if (getc(F) =~ /^\D/o);
269     close F;
270
271     my $batch = new MARC::Batch ($marctype, $filename);
272     $batch->strict_off;
273
274     my $response_scale = 10;
275     my $count = 0;
276     my $r = -1;
277     while (try { $r = $batch->next } otherwise { $r = -1 }) {
278         if ($r == -1) {
279             $logger->warn("Processing of record $count in set $filename failed.  Skipping this record");
280             $count++;
281         }
282
283         $logger->info("processing record $count");
284
285         try {
286             (my $xml = $r->as_xml_record()) =~ s/\n//sog;
287             $xml =~ s/^<\?xml.+\?\s*>//go;
288             $xml =~ s/>\s+</></go;
289             $xml =~ s/\p{Cc}//go;
290             $xml = $U->entityize($xml);
291             $xml =~ s/[\x00-\x1f]//go;
292
293             my $qrec;
294             # Check the leader to ensure we've got something resembling the expected
295             # Allow spaces to give records the benefit of the doubt
296             my $ldr_type = substr($r->leader(), 6, 1);
297             if ($type eq 'bib' && ($record_types{$ldr_type}) eq 'bib' || $ldr_type eq ' ') {
298                 $qrec = _add_bib_rec( $e, $xml, $queue_id, $purpose, $bib_source ) or return $e->die_event;
299             } elsif ($type eq 'auth' && ($record_types{$ldr_type}) eq 'auth' || $ldr_type eq ' ') {
300                 $qrec = _add_auth_rec( $e, $xml, $queue_id, $purpose ) or return $e->die_event;
301             } else {
302                 # I don't know how to handle this type; rock on
303                 $logger->error("In process_spool(), type was $type and leader type was $ldr_type ; not currently supported");
304                 next;
305             }
306
307             if($self->api_name =~ /stream_results/ and $qrec) {
308                 $client->respond($qrec->id)
309             } else {
310                 $client->respond($count) if (++$count % $response_scale) == 0;
311                 $response_scale *= 10 if ($count == ($response_scale * 10));
312             }
313         } catch Error with {
314             my $error = shift;
315             $logger->warn("Encountered a bad record at Vandelay ingest: ".$error);
316         }
317     }
318
319     $e->commit;
320     unlink($filename);
321     $cache->delete_cache('vandelay_import_spool_' . $fingerprint) if $fingerprint;
322     return $count;
323 }
324
325 __PACKAGE__->register_method(  
326     api_name    => "open-ils.vandelay.bib.process_spool",
327     method      => "process_spool",
328     api_level   => 1,
329     argc        => 3,
330     max_chunk_size => 0,
331     record_type => 'bib'
332 );                      
333 __PACKAGE__->register_method(  
334     api_name    => "open-ils.vandelay.auth.process_spool",
335     method      => "process_spool",
336     api_level   => 1,
337     argc        => 3,
338     max_chunk_size => 0,
339     record_type => 'auth'
340 );                      
341
342 __PACKAGE__->register_method(  
343     api_name    => "open-ils.vandelay.bib.process_spool.stream_results",
344     method      => "process_spool",
345     api_level   => 1,
346     argc        => 3,
347     stream      => 1,
348     max_chunk_size => 0,
349     record_type => 'bib'
350 );                      
351 __PACKAGE__->register_method(  
352     api_name    => "open-ils.vandelay.auth.process_spool.stream_results",
353     method      => "process_spool",
354     api_level   => 1,
355     argc        => 3,
356     stream      => 1,
357     max_chunk_size => 0,
358     record_type => 'auth'
359 );
360
361 __PACKAGE__->register_method(  
362     api_name    => "open-ils.vandelay.bib_queue.records.retrieve",
363     method      => 'retrieve_queued_records',
364     api_level   => 1,
365     argc        => 2,
366     stream      => 1,
367     record_type => 'bib'
368 );
369 __PACKAGE__->register_method(  
370     api_name    => "open-ils.vandelay.auth_queue.records.retrieve",
371     method      => 'retrieve_queued_records',
372     api_level   => 1,
373     argc        => 2,
374     stream      => 1,
375     record_type => 'auth'
376 );
377
378 __PACKAGE__->register_method(  
379     api_name    => "open-ils.vandelay.bib_queue.records.matches.retrieve",
380     method      => 'retrieve_queued_records',
381     api_level   => 1,
382     argc        => 2,
383     stream      => 1,
384     record_type => 'bib',
385     signature   => {
386         desc => q/Only retrieve queued bib records that have matches against existing records/
387     }
388 );
389 __PACKAGE__->register_method(  
390     api_name    => "open-ils.vandelay.auth_queue.records.matches.retrieve",
391     method      => 'retrieve_queued_records',
392     api_level   => 1,
393     argc        => 2,
394     stream      => 1,
395     record_type => 'auth',
396     signature   => {
397         desc => q/Only retrieve queued authority records that have matches against existing records/
398     }
399
400 );
401
402 sub retrieve_queued_records {
403     my($self, $conn, $auth, $queue_id, $options) = @_;
404     my $e = new_editor(authtoken => $auth, xact => 1);
405     return $e->die_event unless $e->checkauth;
406     $options ||= {};
407     my $limit = $$options{limit} || 20;
408     my $offset = $$options{offset} || 0;
409
410     my $type = $self->{record_type};
411     my $queue;
412     if($type eq 'bib') {
413         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
414     } else {
415         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
416     }
417     my $evt = check_queue_perms($e, $type, $queue);
418     return $evt if ($evt);
419
420     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
421     my $search = ($type eq 'bib') ? 
422         'search_vandelay_queued_bib_record' : 'search_vandelay_queued_authority_record';
423     my $retrieve = ($type eq 'bib') ? 
424         'retrieve_vandelay_queued_bib_record' : 'retrieve_vandelay_queued_authority_record';
425
426     my $filter = ($$options{non_imported}) ? {import_time => undef} : {};
427
428     my $record_ids;
429     if($self->api_name =~ /matches/) {
430         # fetch only matched records
431         $record_ids = queued_records_with_matches($e, $type, $queue_id, $limit, $offset, $filter);
432     } else {
433         # fetch all queue records
434         $record_ids = $e->$search([
435                 {queue => $queue_id, %$filter}, 
436                 {order_by => {$class => 'id'}, limit => $limit, offset => $offset}
437             ],
438             {idlist => 1}
439         );
440     }
441
442
443     for my $rec_id (@$record_ids) {
444         my $params = {   
445             flesh => 1,
446             flesh_fields => {$class => ['attributes', 'matches']},
447         };
448         my $rec = $e->$retrieve([$rec_id, $params]);
449         $rec->clear_marc if $$options{clear_marc};
450         $conn->respond($rec);
451     }
452     $e->rollback;
453     return undef;
454 }
455
456 sub check_queue_perms {
457     my($e, $type, $queue) = @_;
458     if ($type eq 'bib') {
459         return $e->die_event unless
460             ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
461              $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
462     } else {
463         return $e->die_event unless
464             ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
465              $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
466     }
467
468     return undef;
469 }
470
471 __PACKAGE__->register_method(  
472     api_name    => "open-ils.vandelay.bib_record.list.import",
473     method      => 'import_record_list',
474     api_level   => 1,
475     argc        => 2,
476     stream      => 1,
477     record_type => 'bib'
478 );
479
480 __PACKAGE__->register_method(  
481     api_name    => "open-ils.vandelay.auth_record.list.import",
482     method      => 'import_record_list',
483     api_level   => 1,
484     argc        => 2,
485     stream      => 1,
486     record_type => 'auth'
487 );
488
489 sub import_record_list {
490     my($self, $conn, $auth, $rec_ids, $args) = @_;
491     my $e = new_editor(authtoken => $auth, xact => 1);
492     return $e->die_event unless $e->checkauth;
493     $args ||= {};
494     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $args);
495     $e->rollback;
496     return $err if $err;
497     return {complete => 1};
498 }
499
500
501 __PACKAGE__->register_method(  
502     api_name    => "open-ils.vandelay.bib_queue.import",
503     method      => 'import_queue',
504     api_level   => 1,
505     argc        => 2,
506     stream      => 1,
507     max_chunk_size => 0,
508     record_type => 'bib'
509 );
510
511 __PACKAGE__->register_method(  
512     api_name    => "open-ils.vandelay.auth_queue.import",
513     method      => 'import_queue',
514     api_level   => 1,
515     argc        => 2,
516     stream      => 1,
517     max_chunk_size => 0,
518     record_type => 'auth'
519 );
520 __PACKAGE__->register_method(  
521     api_name    => "open-ils.vandelay.bib_queue.nomatch.import",
522     method      => 'import_queue',
523     api_level   => 1,
524     argc        => 2,
525     stream      => 1,
526     signature   => {
527         desc => q/Only import records that have no collisions/
528     },
529     max_chunk_size => 0,
530     record_type => 'bib'
531 );
532
533 __PACKAGE__->register_method(  
534     api_name    => "open-ils.vandelay.auth_queue.nomatch.import",
535     method      => 'import_queue',
536     api_level   => 1,
537     argc        => 2,
538     stream      => 1,
539     signature   => {
540         desc => q/Only import records that have no collisions/
541     },
542     max_chunk_size => 0,
543     record_type => 'auth'
544 );
545 sub import_queue {
546     my($self, $conn, $auth, $q_id, $options) = @_;
547     my $e = new_editor(authtoken => $auth, xact => 1);
548     return $e->die_event unless $e->checkauth;
549     $options ||= {};
550     my $type = $self->{record_type};
551     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
552
553     my $query = {queue => $q_id, import_time => undef};
554
555     if($self->api_name =~ /nomatch/) {
556         my $matched_recs = queued_records_with_matches($e, $type, $q_id, undef, undef, {import_time => undef});
557         $query->{id} = {'not in' => $matched_recs} if @$matched_recs;
558     }
559
560     my $search = ($type eq 'bib') ? 
561         'search_vandelay_queued_bib_record' : 'search_vandelay_queued_authority_record';
562     my $rec_ids = $e->$search($query, {idlist => 1});
563     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $options);
564     try {$e->rollback} otherwise {}; # only using this to make the read authoritative -- don't die from it
565     return $err if $err;
566     return {complete => 1};
567 }
568
569 # returns a list of queued record IDs for a given queue that 
570 # have at least one entry in the match table
571 sub queued_records_with_matches {
572     my($e, $type, $q_id, $limit, $offset, $filter) = @_;
573
574     my $match_class = 'vbm';
575     my $rec_class = 'vqbr';
576     if($type eq 'auth') {
577         $match_class = 'vam';
578          $rec_class = 'vqar';
579     }
580
581     $filter ||= {};
582     $filter->{queue} = $q_id;
583
584     my $query = {
585         distinct => 1, 
586         select => {$match_class => ['queued_record']}, 
587         from => {
588             $match_class => {
589                 $rec_class => {
590                     field => 'id',
591                     fkey => 'queued_record',
592                     filter => $filter,
593                 }
594             }
595         }
596     };        
597
598     if($limit or defined $offset) {
599         $limit ||= 20;
600         $offset ||= 0;
601         $query->{limit} = $limit;
602         $query->{offset} = $offset;
603     }
604
605     my $data = $e->json_query($query);
606     return [ map {$_->{queued_record}} @$data ];
607 }
608
609 sub import_record_list_impl {
610     my($self, $conn, $rec_ids, $requestor, $args) = @_;
611
612     my $overlay_map = $args->{overlay_map} || {};
613     my $type = $self->{record_type};
614     my $total = @$rec_ids;
615     my $count = 0;
616     my %queues;
617
618     my $step = 1;
619
620     my $auto_overlay_exact = $$args{auto_overlay_exact};
621     my $auto_overlay_1match = $$args{auto_overlay_1match};
622     my $merge_profile = $$args{merge_profile};
623     my $bib_source = $$args{bib_source};
624     my $report_all = $$args{report_all};
625
626     my $overlay_func = 'vandelay.overlay_bib_record';
627     my $auto_overlay_func = 'vandelay.auto_overlay_bib_record';
628     my $retrieve_func = 'retrieve_vandelay_queued_bib_record';
629     my $update_func = 'update_vandelay_queued_bib_record';
630     my $search_func = 'search_vandelay_queued_bib_record';
631     my $retrieve_queue_func = 'retrieve_vandelay_bib_queue';
632     my $update_queue_func = 'update_vandelay_bib_queue';
633     my $rec_class = 'vqbr';
634
635     my %bib_sources;
636     my $editor = new_editor();
637     my $sources = $editor->search_config_bib_source({id => {'!=' => undef}});
638
639     foreach my $src (@$sources) {
640         $bib_sources{$src->id} = $src->source;
641     }
642
643     if($type eq 'auth') {
644         $overlay_func =~ s/bib/auth/o;
645         $auto_overlay_func = s/bib/auth/o;
646         $retrieve_func =~ s/bib/authority/o;
647         $retrieve_queue_func =~ s/bib/authority/o;
648         $update_queue_func =~ s/bib/authority/o;
649         $update_func =~ s/bib/authority/o;
650         $search_func =~ s/bib/authority/o;
651         $rec_class = 'vqar';
652     }
653
654     my @success_rec_ids;
655     for my $rec_id (@$rec_ids) {
656
657         my $overlay_target = $overlay_map->{$rec_id};
658
659         my $error = 0;
660         my $e = new_editor(xact => 1);
661         $e->requestor($requestor);
662
663         my $rec = $e->$retrieve_func([
664             $rec_id,
665             {   flesh => 1,
666                 flesh_fields => { $rec_class => ['matches']},
667             }
668         ]);
669
670         unless($rec) {
671             $conn->respond({total => $total, progress => ++$count, imported => $rec_id, err_event => $e->event});
672             $e->rollback;
673             next;
674         }
675
676         if($rec->import_time) {
677             $e->rollback;
678             next;
679         }
680
681         $queues{$rec->queue} = 1;
682
683         my $record;
684         my $imported = 0;
685
686         if(defined $overlay_target) {
687             # Caller chose an explicit overlay target
688
689             my $res = $e->json_query(
690                 {
691                     from => [
692                         $overlay_func,
693                         $rec->id, 
694                         $overlay_target, 
695                         $merge_profile
696                     ]
697                 }
698             );
699
700             if($res and ($res = $res->[0])) {
701
702                 if($res->{$overlay_func} eq 't') {
703                     $logger->info("vl: $type direct overlay succeeded for queued rec " . 
704                         $rec->id . " and overlay target $overlay_target");
705                     $imported = 1;
706                 }
707
708             } else {
709                 $error = 1;
710                 $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
711             }
712
713         } else {
714
715             if($auto_overlay_1match) { 
716                 # caller says to overlay if there is exactly 1 match
717
718                 my %match_recs = map { $_->eg_record => 1 } @{$rec->matches};
719
720                 if( scalar(keys %match_recs) == 1) { # all matches point to the same record
721
722                     my $res = $e->json_query(
723                         {
724                             from => [
725                                 $overlay_func,
726                                 $rec->id, 
727                                 $rec->matches->[0]->eg_record,
728                                 $merge_profile
729                             ]
730                         }
731                     );
732
733                     if($res and ($res = $res->[0])) {
734     
735                         if($res->{$overlay_func} eq 't') {
736                             $logger->info("vl: $type overlay-1match succeeded for queued rec " . $rec->id);
737                             $imported = 1;
738                         }
739
740                     } else {
741                         $error = 1;
742                         $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
743                     }
744                 }
745             }
746
747             if(!$imported and !$error and $auto_overlay_exact and scalar(@{$rec->matches}) == 1 ) {
748                 
749                 # caller says to overlay if there is an /exact/ match
750
751                 my $res = $e->json_query(
752                     {
753                         from => [
754                             $auto_overlay_func,
755                             $rec->id, 
756                             $merge_profile
757                         ]
758                     }
759                 );
760
761                 if($res and ($res = $res->[0])) {
762
763                     if($res->{$auto_overlay_func} eq 't') {
764                         $logger->info("vl: $type auto-overlay succeeded for queued rec " . $rec->id);
765                         $imported = 1;
766                     }
767
768                 } else {
769                     $error = 1;
770                     $logger->error("vl: Error attempting overlay with func=$auto_overlay_func, profile=$merge_profile, record=$rec_id");
771                 }
772             }
773
774             if(!$imported and !$error) {
775             
776                 # No overlay / merge occurred.  Do a traditional record import by creating a new record
777             
778                 if($type eq 'bib') {
779                     $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import($e, $rec->marc, $bib_sources{$rec->bib_source});
780                 } else {
781
782                     $record = OpenILS::Application::Cat::AuthCommon->import_authority_record($e, $rec->marc); #$source);
783                 }
784
785                 if($U->event_code($record)) {
786
787                     $e->event($record); 
788                     $e->rollback;
789
790                 } else {
791
792                     $logger->info("vl: successfully imported new $type record");
793                     $rec->imported_as($record->id);
794                     $rec->import_time('now');
795
796                     $imported = 1 if $e->$update_func($rec);
797                 }
798             }
799         }
800
801         if($imported) {
802             push @success_rec_ids, $rec_id;
803             $e->commit;
804         } else {
805             # Send an update whenever there's an error
806             $conn->respond({total => $total, progress => ++$count, imported => $rec_id, err_event => $e->event});
807         }
808
809         if($report_all or (++$count % $step) == 0) {
810             $conn->respond({total => $total, progress => $count, imported => $rec_id});
811             # report often at first, climb quickly, then hold steady
812             $step *= 2 unless $step == 256;
813         }
814     }
815
816     # see if we need to mark any queues as complete
817     for my $q_id (keys %queues) {
818
819         my $e = new_editor(xact => 1);
820         my $remaining = $e->$search_func(
821             [{queue => $q_id, import_time => undef}, {limit =>1}], {idlist => 1});
822
823         unless(@$remaining) {
824             my $queue = $e->$retrieve_queue_func($q_id);
825
826             unless($U->is_true($queue->complete)) {
827                 $queue->complete('t');
828                 $e->$update_queue_func($queue) or return $e->die_event;
829                 $e->commit;
830                 next;
831             }
832         } 
833         $e->rollback;
834     }
835
836     import_record_asset_list_impl($conn, \@success_rec_ids, $requestor);
837
838     $conn->respond({total => $total, progress => $count});
839     return undef;
840 }
841
842
843 __PACKAGE__->register_method(  
844     api_name    => "open-ils.vandelay.bib_queue.owner.retrieve",
845     method      => 'owner_queue_retrieve',
846     api_level   => 1,
847     argc        => 2,
848     stream      => 1,
849     record_type => 'bib'
850 );
851 __PACKAGE__->register_method(  
852     api_name    => "open-ils.vandelay.authority_queue.owner.retrieve",
853     method      => 'owner_queue_retrieve',
854     api_level   => 1,
855     argc        => 2,
856     stream      => 1,
857     record_type => 'auth'
858 );
859
860 sub owner_queue_retrieve {
861     my($self, $conn, $auth, $owner_id, $filters) = @_;
862     my $e = new_editor(authtoken => $auth, xact => 1);
863     return $e->die_event unless $e->checkauth;
864     $owner_id = $e->requestor->id; # XXX add support for viewing other's queues?
865     my $queues;
866     $filters ||= {};
867     my $search = {owner => $owner_id};
868     $search->{$_} = $filters->{$_} for keys %$filters;
869
870     if($self->{record_type} eq 'bib') {
871         $queues = $e->search_vandelay_bib_queue(
872             [$search, {order_by => {vbq => 'evergreen.lowercase(name)'}}]);
873     } else {
874         $queues = $e->search_vandelay_authority_queue(
875             [$search, {order_by => {vaq => 'evergreen.lowercase(name)'}}]);
876     }
877     $conn->respond($_) for @$queues;
878     $e->rollback;
879     return undef;
880 }
881
882 __PACKAGE__->register_method(  
883     api_name    => "open-ils.vandelay.bib_queue.delete",
884     method      => "delete_queue",
885     api_level   => 1,
886     argc        => 2,
887     record_type => 'bib'
888 );            
889 __PACKAGE__->register_method(  
890     api_name    => "open-ils.vandelay.auth_queue.delete",
891     method      => "delete_queue",
892     api_level   => 1,
893     argc        => 2,
894     record_type => 'auth'
895 );  
896
897 sub delete_queue {
898     my($self, $conn, $auth, $q_id) = @_;
899     my $e = new_editor(xact => 1, authtoken => $auth);
900     return $e->die_event unless $e->checkauth;
901     if($self->{record_type} eq 'bib') {
902         return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
903         my $queue = $e->retrieve_vandelay_bib_queue($q_id)
904             or return $e->die_event;
905         $e->delete_vandelay_bib_queue($queue)
906             or return $e->die_event;
907     } else {
908            return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
909         my $queue = $e->retrieve_vandelay_authority_queue($q_id)
910             or return $e->die_event;
911         $e->delete_vandelay_authority_queue($queue)
912             or return $e->die_event;
913     }
914     $e->commit;
915     return 1;
916 }
917
918
919 __PACKAGE__->register_method(  
920     api_name    => "open-ils.vandelay.queued_bib_record.html",
921     method      => 'queued_record_html',
922     api_level   => 1,
923     argc        => 2,
924     stream      => 1,
925     record_type => 'bib'
926 );
927 __PACKAGE__->register_method(  
928     api_name    => "open-ils.vandelay.queued_authority_record.html",
929     method      => 'queued_record_html',
930     api_level   => 1,
931     argc        => 2,
932     stream      => 1,
933     record_type => 'auth'
934 );
935
936 sub queued_record_html {
937     my($self, $conn, $auth, $rec_id) = @_;
938     my $e = new_editor(xact=>1,authtoken => $auth);
939     return $e->die_event unless $e->checkauth;
940     my $rec;
941     if($self->{record_type} eq 'bib') {
942         $rec = $e->retrieve_vandelay_queued_bib_record($rec_id)
943             or return $e->die_event;
944     } else {
945         $rec = $e->retrieve_vandelay_queued_authority_record($rec_id)
946             or return $e->die_event;
947     }
948
949     $e->rollback;
950     return $U->simplereq(
951         'open-ils.search',
952         'open-ils.search.biblio.record.html', undef, 1, $rec->marc);
953 }
954
955
956 __PACKAGE__->register_method(  
957     api_name    => "open-ils.vandelay.bib_queue.summary.retrieve", 
958     method      => 'retrieve_queue_summary',
959     api_level   => 1,
960     argc        => 2,
961     stream      => 1,
962     record_type => 'bib'
963 );
964 __PACKAGE__->register_method(  
965     api_name    => "open-ils.vandelay.auth_queue.summary.retrieve",
966     method      => 'retrieve_queue_summary',
967     api_level   => 1,
968     argc        => 2,
969     stream      => 1,
970     record_type => 'auth'
971 );
972
973 sub retrieve_queue_summary {
974     my($self, $conn, $auth, $queue_id) = @_;
975     my $e = new_editor(xact=>1, authtoken => $auth);
976     return $e->die_event unless $e->checkauth;
977
978     my $queue;
979     my $type = $self->{record_type};
980     if($type eq 'bib') {
981         $queue = $e->retrieve_vandelay_bib_queue($queue_id)
982             or return $e->die_event;
983     } else {
984         $queue = $e->retrieve_vandelay_authority_queue($queue_id)
985             or return $e->die_event;
986     }
987
988     my $evt = check_queue_perms($e, $type, $queue);
989     return $evt if $evt;
990
991     my $search = 'search_vandelay_queued_bib_record';
992     $search =~ s/bib/authority/ if $type ne 'bib';
993
994     return {
995         queue => $queue,
996         total => scalar(@{$e->$search({queue => $queue_id}, {idlist=>1})}),
997         imported => scalar(@{$e->$search({queue => $queue_id, import_time => {'!=' => undef}}, {idlist=>1})}),
998     };
999 }
1000
1001 # --------------------------------------------------------------------------------
1002 # Given a list of queued record IDs, imports all items attached to those records
1003 # --------------------------------------------------------------------------------
1004 sub import_record_asset_list_impl {
1005     my($conn, $rec_ids, $requestor) = @_;
1006
1007     my $total = @$rec_ids;
1008     my $try_count = 0;
1009     my $in_count = 0;
1010     my $roe = new_editor(xact=> 1, requestor => $requestor);
1011
1012     for my $rec_id (@$rec_ids) {
1013         my $rec = $roe->retrieve_vandelay_queued_bib_record($rec_id);
1014         next unless $rec and $rec->import_time;
1015         my $item_ids = $roe->search_vandelay_import_item({record => $rec->id}, {idlist=>1});
1016
1017         for my $item_id (@$item_ids) {
1018             my $e = new_editor(requestor => $requestor, xact => 1);
1019             my $item = $e->retrieve_vandelay_import_item($item_id);
1020             $try_count++;
1021
1022             # --------------------------------------------------------------------------------
1023             # Find or create the volume
1024             # --------------------------------------------------------------------------------
1025             my ($vol, $evt) =
1026                 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1027                     $e, $item->call_number, $rec->imported_as, $item->owning_lib);
1028
1029             if($evt) {
1030                 respond_with_status($conn, $total, $try_count, $in_count, $evt);
1031                 next;
1032             }
1033
1034             # --------------------------------------------------------------------------------
1035             # Create the new copy
1036             # --------------------------------------------------------------------------------
1037             my $copy = Fieldmapper::asset::copy->new;
1038             $copy->loan_duration(2);
1039             $copy->fine_level(2);
1040             $copy->barcode($item->barcode);
1041             $copy->location($item->location);
1042             $copy->circ_lib($item->circ_lib || $item->owning_lib);
1043             $copy->status($item->status || OILS_COPY_STATUS_IN_PROCESS);
1044             $copy->circulate($item->circulate);
1045             $copy->deposit($item->deposit);
1046             $copy->deposit_amount($item->deposit_amount);
1047             $copy->ref($item->ref);
1048             $copy->holdable($item->holdable);
1049             $copy->price($item->price);
1050             $copy->circ_as_type($item->circ_as_type);
1051             $copy->alert_message($item->alert_message);
1052             $copy->opac_visible($item->opac_visible);
1053             $copy->circ_modifier($item->circ_modifier);
1054
1055             # --------------------------------------------------------------------------------
1056             # see if a valid circ_modifier was provided
1057             # --------------------------------------------------------------------------------
1058             #if($copy->circ_modifier and not $e->retrieve_config_circ_modifier($item->circ_modifier)) {
1059             if($copy->circ_modifier and not $e->search_config_circ_modifier({code=>$item->circ_modifier})->[0]) {
1060                 respond_with_status($conn, $total, $try_count, $in_count, $e->die_event);
1061                 next;
1062             }
1063
1064             if($evt = OpenILS::Application::Cat::AssetCommon->create_copy($e, $vol, $copy)) {
1065                 try { $e->rollback } otherwise {}; # sometimes calls die_event, sometimes not
1066                 respond_with_status($conn, $total, $try_count, $in_count, $evt);
1067                 next;
1068             }
1069
1070             # --------------------------------------------------------------------------------
1071             # create copy notes
1072             # --------------------------------------------------------------------------------
1073             $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1074                 $e, $copy, '', $item->pub_note, 1) if $item->pub_note;
1075
1076             if($evt) {
1077                 respond_with_status($conn, $total, $try_count, $in_count, $evt);
1078                 next;
1079             }
1080
1081             $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1082                 $e, $copy, '', $item->priv_note, 1) if $item->priv_note;
1083
1084             if($evt) {
1085                 respond_with_status($conn, $total, $try_count, $in_count, $evt);
1086                 next;
1087             }
1088
1089             # --------------------------------------------------------------------------------
1090             # Item import succeeded
1091             # --------------------------------------------------------------------------------
1092             $e->commit;
1093             respond_with_status($conn, $total, $try_count, ++$in_count, undef, imported_as => $copy->id);
1094         }
1095     }
1096     $roe->rollback;
1097     return undef;
1098 }
1099
1100
1101 sub respond_with_status {
1102     my($conn, $total, $try_count, $success_count, $err, %args) = @_;
1103     $conn->respond({
1104         total => $total, 
1105         progress => $try_count, 
1106         err_event => $err, 
1107         success_count => $success_count, %args }) if $err or ($try_count % 5 == 0);
1108 }
1109
1110
1111 1;