]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Vandelay.pm
Strip configured fields during import/overlay
[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 OpenILS::Utils::Normalize qw/clean_marc/;
13 use MARC::Batch;
14 use MARC::Record;
15 use MARC::File::XML ( BinaryEncoding => 'UTF-8' );
16 use Time::HiRes qw(time);
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use MIME::Base64;
19 use XML::LibXML;
20 use OpenILS::Const qw/:const/;
21 use OpenILS::Application::AppUtils;
22 use OpenILS::Application::Cat::BibCommon;
23 use OpenILS::Application::Cat::AuthCommon;
24 use OpenILS::Application::Cat::AssetCommon;
25 my $U = 'OpenILS::Application::AppUtils';
26
27 # A list of LDR/06 values from http://loc.gov/marc
28 my %record_types = (
29         a => 'bib',
30         c => 'bib',
31         d => 'bib',
32         e => 'bib',
33         f => 'bib',
34         g => 'bib',
35         i => 'bib',
36         j => 'bib',
37         k => 'bib',
38         m => 'bib',
39         o => 'bib',
40         p => 'bib',
41         r => 'bib',
42         t => 'bib',
43         u => 'holdings',
44         v => 'holdings',
45         x => 'holdings',
46         y => 'holdings',
47         z => 'auth',
48       ' ' => 'bib',
49 );
50
51 sub initialize {}
52 sub child_init {}
53
54 # --------------------------------------------------------------------------------
55 # Biblio ingest
56
57 sub create_bib_queue {
58     my $self = shift;
59     my $client = shift;
60     my $auth = shift;
61     my $name = shift;
62     my $owner = shift;
63     my $type = shift;
64     my $match_set = shift;
65     my $import_def = shift;
66
67     my $e = new_editor(authtoken => $auth, xact => 1);
68
69     return $e->die_event unless $e->checkauth;
70     return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
71     $owner ||= $e->requestor->id;
72
73     if ($e->search_vandelay_bib_queue( {name => $name, owner => $owner, queue_type => $type})->[0]) {
74         $e->rollback;
75         return OpenILS::Event->new('BIB_QUEUE_EXISTS') 
76     }
77
78     my $queue = new Fieldmapper::vandelay::bib_queue();
79     $queue->name( $name );
80     $queue->owner( $owner );
81     $queue->queue_type( $type ) if ($type);
82     $queue->item_attr_def( $import_def ) if ($import_def);
83     $queue->match_set($match_set) if $match_set;
84
85     my $new_q = $e->create_vandelay_bib_queue( $queue );
86     return $e->die_event unless ($new_q);
87     $e->commit;
88
89     return $new_q;
90 }
91 __PACKAGE__->register_method(  
92     api_name   => "open-ils.vandelay.bib_queue.create",
93     method     => "create_bib_queue",
94     api_level  => 1,
95     argc       => 4,
96 );                      
97
98
99 sub create_auth_queue {
100     my $self = shift;
101     my $client = shift;
102     my $auth = shift;
103     my $name = shift;
104     my $owner = shift;
105     my $type = shift;
106     my $match_set = shift;
107
108     my $e = new_editor(authtoken => $auth, xact => 1);
109
110     return $e->die_event unless $e->checkauth;
111     return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
112     $owner ||= $e->requestor->id;
113
114     if ($e->search_vandelay_authority_queue({name => $name, owner => $owner, queue_type => $type})->[0]) {
115         $e->rollback;
116         return OpenILS::Event->new('AUTH_QUEUE_EXISTS') 
117     }
118
119     my $queue = new Fieldmapper::vandelay::authority_queue();
120     $queue->name( $name );
121     $queue->owner( $owner );
122     $queue->queue_type( $type ) if ($type);
123
124     my $new_q = $e->create_vandelay_authority_queue( $queue );
125     $e->die_event unless ($new_q);
126     $e->commit;
127
128     return $new_q;
129 }
130 __PACKAGE__->register_method(  
131     api_name   => "open-ils.vandelay.authority_queue.create",
132     method     => "create_auth_queue",
133     api_level  => 1,
134     argc       => 3,
135 );                      
136
137 sub add_record_to_bib_queue {
138     my $self = shift;
139     my $client = shift;
140     my $auth = shift;
141     my $queue = shift;
142     my $marc = shift;
143     my $purpose = shift;
144     my $bib_source = shift;
145
146     my $e = new_editor(authtoken => $auth, xact => 1);
147
148     $queue = $e->retrieve_vandelay_bib_queue($queue);
149
150     return $e->die_event unless $e->checkauth;
151     return $e->die_event unless
152         ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
153          $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
154
155     my $new_rec = _add_bib_rec($e, $marc, $queue->id, $purpose, $bib_source);
156
157     return $e->die_event unless ($new_rec);
158     $e->commit;
159     return $new_rec;
160 }
161 __PACKAGE__->register_method(  
162     api_name   => "open-ils.vandelay.queued_bib_record.create",
163     method     => "add_record_to_bib_queue",
164     api_level  => 1,
165     argc       => 3,
166 );                      
167
168 sub _add_bib_rec {
169     my $e = shift;
170     my $marc = shift;
171     my $queue = shift;
172     my $purpose = shift;
173     my $bib_source = shift;
174
175     my $rec = new Fieldmapper::vandelay::queued_bib_record();
176     $rec->marc( $marc );
177     $rec->queue( $queue );
178     $rec->purpose( $purpose ) if ($purpose);
179     $rec->bib_source($bib_source);
180
181     return $e->create_vandelay_queued_bib_record( $rec );
182 }
183
184 sub add_record_to_authority_queue {
185     my $self = shift;
186     my $client = shift;
187     my $auth = shift;
188     my $queue = shift;
189     my $marc = shift;
190     my $purpose = shift;
191
192     my $e = new_editor(authtoken => $auth, xact => 1);
193
194     $queue = $e->retrieve_vandelay_authority_queue($queue);
195
196     return $e->die_event unless $e->checkauth;
197     return $e->die_event unless
198         ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
199          $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
200
201     my $new_rec = _add_auth_rec($e, $marc, $queue->id, $purpose);
202
203     return $e->die_event unless ($new_rec);
204     $e->commit;
205     return $new_rec;
206 }
207 __PACKAGE__->register_method(
208     api_name   => "open-ils.vandelay.queued_authority_record.create",
209     method     => "add_record_to_authority_queue",
210     api_level  => 1,
211     argc       => 3,
212 );
213
214 sub _add_auth_rec {
215     my $e = shift;
216     my $marc = shift;
217     my $queue = shift;
218     my $purpose = shift;
219
220     my $rec = new Fieldmapper::vandelay::queued_authority_record();
221     $rec->marc( $marc );
222     $rec->queue( $queue );
223     $rec->purpose( $purpose ) if ($purpose);
224
225     return $e->create_vandelay_queued_authority_record( $rec );
226 }
227
228 sub process_spool {
229     my $self = shift;
230     my $client = shift;
231     my $auth = shift;
232     my $fingerprint = shift || '';
233     my $queue_id = shift;
234     my $purpose = shift;
235     my $filename = shift;
236     my $bib_source = shift;
237
238     my $e = new_editor(authtoken => $auth, xact => 1);
239     return $e->die_event unless $e->checkauth;
240
241     my $queue;
242     my $type = $self->{record_type};
243
244     if($type eq 'bib') {
245         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
246     } else {
247         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
248     }
249
250     my $evt = check_queue_perms($e, $type, $queue);
251     return $evt if ($evt);
252
253     my $cache = new OpenSRF::Utils::Cache();
254
255     if($fingerprint) {
256         my $data = $cache->get_cache('vandelay_import_spool_' . $fingerprint);
257         $purpose = $data->{purpose};
258         $filename = $data->{path};
259         $bib_source = $data->{bib_source};
260     }
261
262     unless(-r $filename) {
263         $logger->error("unable to read MARC file $filename");
264         return -1; # make this an event XXX
265     }
266
267     $logger->info("vandelay spooling $fingerprint purpose=$purpose file=$filename");
268
269     my $marctype = 'USMARC'; 
270
271     open F, $filename;
272     $marctype = 'XML' if (getc(F) =~ /^\D/o);
273     close F;
274
275     my $batch = new MARC::Batch ($marctype, $filename);
276     $batch->strict_off;
277
278     my $response_scale = 10;
279     my $count = 0;
280     my $r = -1;
281     while (try { $r = $batch->next } otherwise { $r = -1 }) {
282         if ($r == -1) {
283             $logger->warn("Processing of record $count in set $filename failed.  Skipping this record");
284             $count++;
285         }
286
287         $logger->info("processing record $count");
288
289         try {
290             my $xml = clean_marc($r);
291
292             my $qrec;
293             # Check the leader to ensure we've got something resembling the expected
294             # Allow spaces to give records the benefit of the doubt
295             my $ldr_type = substr($r->leader(), 6, 1);
296             if ($type eq 'bib' && ($record_types{$ldr_type}) eq 'bib' || $ldr_type eq ' ') {
297                 $qrec = _add_bib_rec( $e, $xml, $queue_id, $purpose, $bib_source ) or return $e->die_event;
298             } elsif ($type eq 'auth' && ($record_types{$ldr_type}) eq 'auth' || $ldr_type eq ' ') {
299                 $qrec = _add_auth_rec( $e, $xml, $queue_id, $purpose ) or return $e->die_event;
300             } else {
301                 # I don't know how to handle this type; rock on
302                 $logger->error("In process_spool(), type was $type and leader type was $ldr_type ; not currently supported");
303                 next;
304             }
305
306             if($self->api_name =~ /stream_results/ and $qrec) {
307                 $client->respond($qrec->id)
308             } else {
309                 $client->respond($count) if (++$count % $response_scale) == 0;
310                 $response_scale *= 10 if ($count == ($response_scale * 10));
311             }
312         } catch Error with {
313             my $error = shift;
314             $logger->warn("Encountered a bad record at Vandelay ingest: ".$error);
315         }
316     }
317
318     $e->commit;
319     unlink($filename);
320     $cache->delete_cache('vandelay_import_spool_' . $fingerprint) if $fingerprint;
321     return $count;
322 }
323
324 __PACKAGE__->register_method(  
325     api_name    => "open-ils.vandelay.bib.process_spool",
326     method      => "process_spool",
327     api_level   => 1,
328     argc        => 3,
329     max_chunk_size => 0,
330     record_type => 'bib'
331 );                      
332 __PACKAGE__->register_method(  
333     api_name    => "open-ils.vandelay.auth.process_spool",
334     method      => "process_spool",
335     api_level   => 1,
336     argc        => 3,
337     max_chunk_size => 0,
338     record_type => 'auth'
339 );                      
340
341 __PACKAGE__->register_method(  
342     api_name    => "open-ils.vandelay.bib.process_spool.stream_results",
343     method      => "process_spool",
344     api_level   => 1,
345     argc        => 3,
346     stream      => 1,
347     max_chunk_size => 0,
348     record_type => 'bib'
349 );                      
350 __PACKAGE__->register_method(  
351     api_name    => "open-ils.vandelay.auth.process_spool.stream_results",
352     method      => "process_spool",
353     api_level   => 1,
354     argc        => 3,
355     stream      => 1,
356     max_chunk_size => 0,
357     record_type => 'auth'
358 );
359
360 __PACKAGE__->register_method(  
361     api_name    => "open-ils.vandelay.bib_queue.records.retrieve",
362     method      => 'retrieve_queued_records',
363     api_level   => 1,
364     argc        => 2,
365     stream      => 1,
366     record_type => 'bib'
367 );
368 __PACKAGE__->register_method(
369     api_name    => "open-ils.vandelay.bib_queue.records.retrieve.export.print",
370     method      => 'retrieve_queued_records',
371     api_level   => 1,
372     argc        => 2,
373     stream      => 1,
374     record_type => 'bib'
375 );
376 __PACKAGE__->register_method(
377     api_name    => "open-ils.vandelay.bib_queue.records.retrieve.export.csv",
378     method      => 'retrieve_queued_records',
379     api_level   => 1,
380     argc        => 2,
381     stream      => 1,
382     record_type => 'bib'
383 );
384 __PACKAGE__->register_method(
385     api_name    => "open-ils.vandelay.bib_queue.records.retrieve.export.email",
386     method      => 'retrieve_queued_records',
387     api_level   => 1,
388     argc        => 2,
389     stream      => 1,
390     record_type => 'bib'
391 );
392
393 __PACKAGE__->register_method(  
394     api_name    => "open-ils.vandelay.auth_queue.records.retrieve",
395     method      => 'retrieve_queued_records',
396     api_level   => 1,
397     argc        => 2,
398     stream      => 1,
399     record_type => 'auth'
400 );
401 __PACKAGE__->register_method(
402     api_name    => "open-ils.vandelay.auth_queue.records.retrieve.export.print",
403     method      => 'retrieve_queued_records',
404     api_level   => 1,
405     argc        => 2,
406     stream      => 1,
407     record_type => 'auth'
408 );
409 __PACKAGE__->register_method(
410     api_name    => "open-ils.vandelay.auth_queue.records.retrieve.export.csv",
411     method      => 'retrieve_queued_records',
412     api_level   => 1,
413     argc        => 2,
414     stream      => 1,
415     record_type => 'auth'
416 );
417 __PACKAGE__->register_method(
418     api_name    => "open-ils.vandelay.auth_queue.records.retrieve.export.email",
419     method      => 'retrieve_queued_records',
420     api_level   => 1,
421     argc        => 2,
422     stream      => 1,
423     record_type => 'auth'
424 );
425
426 __PACKAGE__->register_method(  
427     api_name    => "open-ils.vandelay.bib_queue.records.matches.retrieve",
428     method      => 'retrieve_queued_records',
429     api_level   => 1,
430     argc        => 2,
431     stream      => 1,
432     record_type => 'bib',
433     signature   => {
434         desc => q/Only retrieve queued bib records that have matches against existing records/
435     }
436 );
437 __PACKAGE__->register_method(  
438     api_name    => "open-ils.vandelay.auth_queue.records.matches.retrieve",
439     method      => 'retrieve_queued_records',
440     api_level   => 1,
441     argc        => 2,
442     stream      => 1,
443     record_type => 'auth',
444     signature   => {
445         desc => q/Only retrieve queued authority records that have matches against existing records/
446     }
447 );
448
449 sub retrieve_queued_records {
450     my($self, $conn, $auth, $queue_id, $options) = @_;
451
452     $options ||= {};
453     my $limit = $$options{limit} || 20;
454     my $offset = $$options{offset} || 0;
455     my $type = $self->{record_type};
456
457     my $e = new_editor(authtoken => $auth, xact => 1);
458     return $e->die_event unless $e->checkauth;
459
460     my $queue;
461     if($type eq 'bib') {
462         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
463     } else {
464         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
465     }
466     my $evt = check_queue_perms($e, $type, $queue);
467     return $evt if ($evt);
468
469     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
470     my $query = {
471         select => {$class => ['id']},
472         from => $class,
473         where => {queue => $queue_id},
474         distinct => 1,
475         order_by => {$class => ['id']}, 
476         limit => $limit,
477         offset => $offset,
478     };
479     if($self->api_name =~ /export/) {
480         delete $query->{limit};
481         delete $query->{offset};
482     }
483
484     $query->{where}->{import_time} = undef if $$options{non_imported};
485
486     if($$options{with_import_error}) {
487
488         $query->{from} = {$class => {vii => {type => 'left'}}};
489         $query->{where}->{'-or'} = [
490             {'+vqbr' => {import_error => {'!=' => undef}}},
491             {'+vii' => {import_error => {'!=' => undef}}}
492         ];
493
494     } else {
495         
496         if($$options{with_rec_import_error}) {
497             $query->{where}->{import_error} = {'!=' => undef};
498
499         } elsif( $$options{with_item_import_error} and $type eq 'bib') {
500
501             $query->{from} = {$class => 'vii'};
502             $query->{where}->{'+vii'} = {import_error => {'!=' => undef}};
503         }
504     }
505
506     if($self->api_name =~ /matches/) {
507         # find only records that have matches
508         my $mclass = $type eq 'bib' ? 'vbm' : 'vam';
509         $query->{from} = {$class => {$mclass => {type => 'right'}}};
510     } 
511
512     my $record_ids = $e->json_query($query);
513
514     my $retrieve = ($type eq 'bib') ? 
515         'retrieve_vandelay_queued_bib_record' : 'retrieve_vandelay_queued_authority_record';
516     my $search = ($type eq 'bib') ? 
517         'search_vandelay_queued_bib_record' : 'search_vandelay_queued_authority_record';
518
519     if ($self->api_name =~ /export/) {
520         my $rec_list = $e->$search({id => [map { $_->{id} } @$record_ids]}, {substream => 1});
521         if ($self->api_name =~ /print/) {
522
523             $e->rollback;
524             return $U->fire_object_event(
525                 undef,
526                 'vandelay.queued_'.$type.'_record.print',
527                 $rec_list,
528                 $e->requestor->ws_ou
529             );
530
531         } elsif ($self->api_name =~ /csv/) {
532
533             $e->rollback;
534             return $U->fire_object_event(
535                 undef,
536                 'vandelay.queued_'.$type.'_record.csv',
537                 $rec_list,
538                 $e->requestor->ws_ou
539             );
540
541         } elsif ($self->api_name =~ /email/) {
542
543             $conn->respond_complete(1);
544
545             for my $rec (@$rec_list) {
546                 $U->create_events_for_hook(
547                     'vandelay.queued_'.$type.'_record.email',
548                     $rec,
549                     $e->requestor->home_ou,
550                     undef,
551                     undef,
552                     1
553                 );
554             }
555
556         }
557     } else {
558         for my $rec_id (@$record_ids) {
559             my $flesh = ['attributes', 'matches'];
560             push(@$flesh, 'import_items') if $$options{flesh_import_items};
561             my $params = {flesh => 1, flesh_fields => {$class => $flesh}};
562             my $rec = $e->$retrieve([$rec_id->{id}, $params]);
563             $rec->clear_marc if $$options{clear_marc};
564             $conn->respond($rec);
565         }
566     }
567
568     $e->rollback;
569     return undef;
570 }
571
572 __PACKAGE__->register_method(  
573     api_name    => 'open-ils.vandelay.import_item.queue.retrieve',
574     method      => 'retrieve_queue_import_items',
575     api_level   => 1,
576     argc        => 2,
577     stream      => 1,
578     authoritative => 1,
579     signature => q/
580         Returns Import Item (vii) objects for the selected queue.
581         Filter options:
582             with_import_error : only return items that failed to import
583     /
584 );
585 __PACKAGE__->register_method(
586     api_name    => 'open-ils.vandelay.import_item.queue.export.print',
587     method      => 'retrieve_queue_import_items',
588     api_level   => 1,
589     argc        => 2,
590     stream      => 1,
591     authoritative => 1,
592     signature => q/
593         Returns template-generated printable output of Import Item (vii) objects for the selected queue.
594         Filter options:
595             with_import_error : only return items that failed to import
596     /
597 );
598 __PACKAGE__->register_method(
599     api_name    => 'open-ils.vandelay.import_item.queue.export.csv',
600     method      => 'retrieve_queue_import_items',
601     api_level   => 1,
602     argc        => 2,
603     stream      => 1,
604     authoritative => 1,
605     signature => q/
606         Returns template-generated CSV output of Import Item (vii) objects for the selected queue.
607         Filter options:
608             with_import_error : only return items that failed to import
609     /
610 );
611 __PACKAGE__->register_method(
612     api_name    => 'open-ils.vandelay.import_item.queue.export.email',
613     method      => 'retrieve_queue_import_items',
614     api_level   => 1,
615     argc        => 2,
616     stream      => 1,
617     authoritative => 1,
618     signature => q/
619         Emails template-generated output of Import Item (vii) objects for the selected queue.
620         Filter options:
621             with_import_error : only return items that failed to import
622     /
623 );
624
625 sub retrieve_queue_import_items {
626     my($self, $conn, $auth, $q_id, $options) = @_;
627
628     $options ||= {};
629     my $limit = $$options{limit} || 20;
630     my $offset = $$options{offset} || 0;
631
632     my $e = new_editor(authtoken => $auth);
633     return $e->event unless $e->checkauth;
634
635     my $queue = $e->retrieve_vandelay_bib_queue($q_id) or return $e->event;
636     my $evt = check_queue_perms($e, 'bib', $queue);
637     return $evt if $evt;
638
639     my $query = {
640         select => {vii => ['id']},
641         from => {
642             vii => {
643                 vqbr => {
644                     join => {
645                         'vbq' => {
646                             field => 'id',
647                             fkey => 'queue',
648                             filter => {id => $q_id}
649                         }
650                     }
651                 }
652             }
653         },
654         order_by => {'vii' => ['record','id']},
655         limit => $limit,
656         offset => $offset
657     };
658     if($self->api_name =~ /export/) {
659         delete $query->{limit};
660         delete $query->{offset};
661     }
662
663     $query->{where} = {'+vii' => {import_error => {'!=' => undef}}}
664         if $$options{with_import_error};
665
666     my $items = $e->json_query($query);
667     my $item_list = $e->search_vandelay_import_item({id => [map { $_->{id} } @$items]});
668     if ($self->api_name =~ /export/) {
669         if ($self->api_name =~ /print/) {
670
671             return $U->fire_object_event(
672                 undef,
673                 'vandelay.import_items.print',
674                 $item_list,
675                 $e->requestor->ws_ou
676             );
677
678         } elsif ($self->api_name =~ /csv/) {
679
680             return $U->fire_object_event(
681                 undef,
682                 'vandelay.import_items.csv',
683                 $item_list,
684                 $e->requestor->ws_ou
685             );
686
687         } elsif ($self->api_name =~ /email/) {
688
689             $conn->respond_complete(1);
690
691             for my $item (@$item_list) {
692                 $U->create_events_for_hook(
693                     'vandelay.import_items.email',
694                     $item,
695                     $e->requestor->home_ou,
696                     undef,
697                     undef,
698                     1
699                 );
700             }
701
702         }
703     } else {
704         for my $item (@$item_list) {
705             $conn->respond($item);
706         }
707     }
708
709     return undef;
710 }
711
712 sub check_queue_perms {
713     my($e, $type, $queue) = @_;
714     if ($type eq 'bib') {
715         return $e->die_event unless
716             ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
717              $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
718     } else {
719         return $e->die_event unless
720             ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
721              $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
722     }
723
724     return undef;
725 }
726
727 __PACKAGE__->register_method(  
728     api_name    => "open-ils.vandelay.bib_record.list.import",
729     method      => 'import_record_list',
730     api_level   => 1,
731     argc        => 2,
732     stream      => 1,
733     record_type => 'bib'
734 );
735
736 __PACKAGE__->register_method(  
737     api_name    => "open-ils.vandelay.auth_record.list.import",
738     method      => 'import_record_list',
739     api_level   => 1,
740     argc        => 2,
741     stream      => 1,
742     record_type => 'auth'
743 );
744
745 sub import_record_list {
746     my($self, $conn, $auth, $rec_ids, $args) = @_;
747     my $e = new_editor(authtoken => $auth, xact => 1);
748     return $e->die_event unless $e->checkauth;
749     $args ||= {};
750     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $args);
751     try {$e->rollback} otherwise {}; 
752     return $err if $err;
753     return {complete => 1};
754 }
755
756
757 __PACKAGE__->register_method(  
758     api_name    => "open-ils.vandelay.bib_queue.import",
759     method      => 'import_queue',
760     api_level   => 1,
761     argc        => 2,
762     stream      => 1,
763     max_chunk_size => 0,
764     record_type => 'bib',
765     signature => {
766         desc => q/
767             Attempts to import all non-imported records for the selected queue.
768             Will also attempt import of all non-imported items.
769         /
770     }
771 );
772
773 __PACKAGE__->register_method(  
774     api_name    => "open-ils.vandelay.auth_queue.import",
775     method      => 'import_queue',
776     api_level   => 1,
777     argc        => 2,
778     stream      => 1,
779     max_chunk_size => 0,
780     record_type => 'auth'
781 );
782
783 sub import_queue {
784     my($self, $conn, $auth, $q_id, $options) = @_;
785     my $e = new_editor(authtoken => $auth, xact => 1);
786     return $e->die_event unless $e->checkauth;
787     $options ||= {};
788     my $type = $self->{record_type};
789     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
790
791     # First, collect the not-yet-imported records
792     my $query = {queue => $q_id, import_time => undef};
793     my $search = ($type eq 'bib') ? 
794         'search_vandelay_queued_bib_record' : 
795         'search_vandelay_queued_authority_record';
796     my $rec_ids = $e->$search($query, {idlist => 1});
797
798     # Now add any imported records that have un-imported items
799
800     if($type eq 'bib') {
801         my $item_recs = $e->json_query({
802             select => {vqbr => ['id']},
803             from => {vqbr => 'vii'},
804             where => {
805                 '+vqbr' => {
806                     queue => $q_id,
807                     import_time => {'!=' => undef}
808                 },
809                 '+vii' => {import_time => undef}
810             },
811             distinct => 1
812         });
813         push(@$rec_ids, map {$_->{id}} @$item_recs);
814     }
815
816     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $options);
817     try {$e->rollback} otherwise {}; # only using this to make the read authoritative -- don't die from it
818     return $err if $err;
819     return {complete => 1};
820 }
821
822 # returns a list of queued record IDs for a given queue that 
823 # have at least one entry in the match table
824 # XXX DEPRECATED?
825 sub queued_records_with_matches {
826     my($e, $type, $q_id, $limit, $offset, $filter) = @_;
827
828     my $match_class = 'vbm';
829     my $rec_class = 'vqbr';
830     if($type eq 'auth') {
831         $match_class = 'vam';
832          $rec_class = 'vqar';
833     }
834
835     $filter ||= {};
836     $filter->{queue} = $q_id;
837
838     my $query = {
839         distinct => 1, 
840         select => {$match_class => ['queued_record']}, 
841         from => {
842             $match_class => {
843                 $rec_class => {
844                     field => 'id',
845                     fkey => 'queued_record',
846                     filter => $filter,
847                 }
848             }
849         }
850     };        
851
852     if($limit or defined $offset) {
853         $limit ||= 20;
854         $offset ||= 0;
855         $query->{limit} = $limit;
856         $query->{offset} = $offset;
857     }
858
859     my $data = $e->json_query($query);
860     return [ map {$_->{queued_record}} @$data ];
861 }
862
863
864 sub import_record_list_impl {
865     my($self, $conn, $rec_ids, $requestor, $args) = @_;
866
867     my $overlay_map = $args->{overlay_map} || {};
868     my $type = $self->{record_type};
869     my %queues;
870
871     my $report_args = {
872         progress => 1,
873         step => 1,
874         conn => $conn,
875         total => scalar(@$rec_ids),
876         report_all => $$args{report_all}
877     };
878
879     $conn->max_chunk_count(1) if $$args{report_all};
880
881     my $auto_overlay_exact = $$args{auto_overlay_exact};
882     my $auto_overlay_1match = $$args{auto_overlay_1match};
883     my $auto_overlay_best = $$args{auto_overlay_best_match};
884     my $match_quality_ratio = $$args{match_quality_ratio};
885     my $merge_profile = $$args{merge_profile};
886     my $ft_merge_profile = $$args{fall_through_merge_profile};
887     my $bib_source = $$args{bib_source};
888     my $import_no_match = $$args{import_no_match};
889
890     my $overlay_func = 'vandelay.overlay_bib_record';
891     my $auto_overlay_func = 'vandelay.auto_overlay_bib_record';
892     my $auto_overlay_best_func = 'vandelay.auto_overlay_bib_record_with_best'; # XXX bib-only
893     my $retrieve_func = 'retrieve_vandelay_queued_bib_record';
894     my $update_func = 'update_vandelay_queued_bib_record';
895     my $search_func = 'search_vandelay_queued_bib_record';
896     my $retrieve_queue_func = 'retrieve_vandelay_bib_queue';
897     my $update_queue_func = 'update_vandelay_bib_queue';
898     my $delete_queue_func = 'delete_vandelay_bib_queue';
899     my $rec_class = 'vqbr';
900
901     my $editor = new_editor();
902
903     my %bib_sources;
904     my $sources = $editor->search_config_bib_source({id => {'!=' => undef}});
905     $bib_sources{$_->id} = $_->source for @$sources;
906
907     if($type eq 'auth') {
908         $overlay_func =~ s/bib/auth/o;
909         $auto_overlay_func = s/bib/auth/o;
910         $retrieve_func =~ s/bib/authority/o;
911         $retrieve_queue_func =~ s/bib/authority/o;
912         $update_queue_func =~ s/bib/authority/o;
913         $update_func =~ s/bib/authority/o;
914         $search_func =~ s/bib/authority/o;
915         $delete_queue_func =~ s/bib/authority/o;
916         $rec_class = 'vqar';
917     }
918
919     my $import_loc = $requestor->ws_ou;
920     my $ancestors = $U->get_org_ancestors($import_loc) if ($import_loc);
921     my $trash_tags = $editor->search_vandelay_import_bib_trash_fields({owner => $ancestors}) if ($ancestors);
922
923     my $new_rec_perm_cache;
924     my @success_rec_ids;
925     for my $rec_id (@$rec_ids) {
926
927         my $error = 0;
928         my $overlay_target = $overlay_map->{$rec_id};
929
930         my $e = new_editor(xact => 1);
931         $e->requestor($requestor);
932
933         $$report_args{e} = $e;
934         $$report_args{evt} = undef;
935         $$report_args{import_error} = undef;
936         $$report_args{no_import} = 0;
937
938         my $rec = $e->$retrieve_func([
939             $rec_id,
940             {   flesh => 1,
941                 flesh_fields => { $rec_class => ['matches']},
942             }
943         ]);
944
945         unless($rec) {
946             $$report_args{evt} = $e->event;
947             finish_rec_import_attempt($report_args);
948             next;
949         }
950
951         if($rec->import_time) {
952             # if the record is already imported, that means it may have 
953             # un-imported copies.  Add to success list for later processing.
954             push(@success_rec_ids, $rec_id);
955             $e->rollback;
956             next;
957         }
958
959         if ($trash_tags && @$trash_tags) {
960             my $marcxml = XML::LibXML->new->parse_string($rec->marc);
961             if ($marcxml) {
962                 for my $tag (@$trash_tags) {
963                     for my $node ($marcxml->findnodes('//*[@tag="'.$tag->field.'"]')) {
964                         $node->parentNode->removeChild($node);
965                     }
966                 }
967
968                 $rec->marc( $U->entityize( $marcdoc->documentElement->toString ) );
969                 $e->$update_func($rec);
970             }
971         }
972
973         $$report_args{rec} = $rec;
974         $queues{$rec->queue} = 1;
975
976         my $record;
977         my $imported = 0;
978
979         if(defined $overlay_target) {
980             # Caller chose an explicit overlay target
981
982             my $res = $e->json_query(
983                 {
984                     from => [
985                         $overlay_func,
986                         $rec_id,
987                         $overlay_target, 
988                         $merge_profile
989                     ]
990                 }
991             );
992
993             if($res and ($res = $res->[0])) {
994
995                 if($res->{$overlay_func} eq 't') {
996                     $logger->info("vl: $type direct overlay succeeded for queued rec ".
997                         "$rec_id and overlay target $overlay_target");
998                     $imported = 1;
999                 }
1000
1001             } else {
1002                 $error = 1;
1003                 $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
1004             }
1005
1006         } else {
1007
1008             if($auto_overlay_1match) { # overlay if there is exactly 1 match
1009
1010                 my %match_recs = map { $_->eg_record => 1 } @{$rec->matches};
1011
1012                 if( scalar(keys %match_recs) == 1) { # all matches point to the same record
1013
1014                     ($imported, $error, $rec) = try_auto_overlay(
1015                         $e, $type,
1016                         $report_args, 
1017                         $auto_overlay_best_func,
1018                         $retrieve_func,
1019                         $rec_class,
1020                         $rec_id, 
1021                         $match_quality_ratio, 
1022                         $merge_profile, 
1023                         $ft_merge_profile
1024                     );
1025                 }
1026             }
1027
1028             if(!$imported and !$error and $auto_overlay_exact and scalar(@{$rec->matches}) == 1 ) {
1029                 
1030                 # caller says to overlay if there is an /exact/ match
1031                 # $auto_overlay_func only proceeds and returns true on exact matches
1032
1033                 my $res = $e->json_query(
1034                     {
1035                         from => [
1036                             $auto_overlay_func,
1037                             $rec_id,
1038                             $merge_profile
1039                         ]
1040                     }
1041                 );
1042
1043                 if($res and ($res = $res->[0])) {
1044
1045                     if($res->{$auto_overlay_func} eq 't') {
1046                         $logger->info("vl: $type auto-overlay succeeded for queued rec $rec_id");
1047                         $imported = 1;
1048
1049                         # re-fetch the record to pick up the imported_as value from the DB
1050                         $$report_args{rec} = $rec = $e->$retrieve_func([
1051                             $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1052
1053                     } else {
1054                         $logger->info("vl: $type auto-overlay failed for queued rec $rec_id");
1055                     }
1056
1057                 } else {
1058                     $error = 1;
1059                     $logger->error("vl: Error attempting overlay with func=$auto_overlay_func, profile=$merge_profile, record=$rec_id");
1060                 }
1061             }
1062
1063             if(!$imported and !$error and $auto_overlay_best and scalar(@{$rec->matches}) > 0 ) {
1064                 # caller says to overlay the best match
1065
1066                 ($imported, $error, $rec) = try_auto_overlay(
1067                     $e, $type,
1068                     $report_args, 
1069                     $auto_overlay_best_func,
1070                     $retrieve_func,
1071                     $rec_class,
1072                     $rec_id, 
1073                     $match_quality_ratio, 
1074                     $merge_profile, 
1075                     $ft_merge_profile
1076                 );
1077             }
1078
1079             if(!$imported and !$error and $import_no_match and scalar(@{$rec->matches}) == 0) {
1080             
1081                 # No overlay / merge occurred.  Do a traditional record import by creating a new record
1082
1083                 if (!$new_rec_perm_cache) {
1084                     $new_rec_perm_cache = {};
1085
1086                     # all users creating new records are required to have the basic permission.
1087                     # if the client requests, we can enforce extra permissions for creating new records.
1088                     # for speed, check the permissions the first time then cache the result.
1089
1090                     my $perm = ($type eq 'bib') ? 'IMPORT_MARC' : 'IMPORT_AUTHORITY_MARC';
1091                     my $xperm = $$args{new_rec_perm};
1092                     my $rec_ou = $e->requestor->ws_ou;
1093
1094                     $new_rec_perm_cache->{evt} = $e->die_event
1095                         if !$e->allowed($perm, $rec_ou) || ($xperm and !$e->allowed($xperm, $rec_ou));
1096                 }
1097
1098                 if ($new_rec_perm_cache->{evt}) {
1099
1100                     # a cached event won't roll back the transaction (a la die_event), but
1101                     # the transaction will get rolled back in finish_rec_import_attempt() below
1102                     $$report_args{evt} = $new_rec_perm_cache->{evt};
1103                     $$report_args{import_error} = 'import.record.perm_failure';
1104
1105                 } else { # perm checks succeeded
1106
1107                     $logger->info("vl: creating new $type record for queued record $rec_id");
1108
1109                     if ($type eq 'bib') {
1110
1111                         $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
1112                             $e, $rec->marc, $bib_sources{$rec->bib_source}, undef, 1);
1113
1114                     } else { # authority record
1115
1116                         $record = OpenILS::Application::Cat::AuthCommon->import_authority_record($e, $rec->marc); #$source);
1117                     }
1118
1119                     if($U->event_code($record)) {
1120                         $$report_args{import_error} = 'import.duplicate.tcn' 
1121                             if $record->{textcode} eq 'OPEN_TCN_NOT_FOUND';
1122                         $$report_args{evt} = $record;
1123
1124                     } else {
1125
1126                         $logger->info("vl: successfully imported new $type record");
1127                         $rec->imported_as($record->id);
1128                         $imported = 1;
1129                     }
1130                 }
1131             }
1132         }
1133
1134         if($imported) {
1135
1136             $rec->import_time('now');
1137             $rec->clear_import_error;
1138             $rec->clear_error_detail;
1139
1140             if($e->$update_func($rec)) {
1141
1142                 if($type eq 'bib') {
1143
1144                     # see if this record is linked from an acq record.
1145                     my $li = $e->search_acq_lineitem(
1146                         {queued_record => $rec->id, state => {'!=' => 'canceled'}})->[0];
1147
1148                     if ($li) { 
1149                         # if so, update the acq lineitem to point to the imported record
1150                         $li->eg_bib_id($rec->imported_as);
1151                         $$report_args{evt} = $e->die_event unless $e->update_acq_lineitem($li);
1152                     }
1153                 }
1154
1155                 push @success_rec_ids, $rec_id;
1156                 finish_rec_import_attempt($report_args);
1157
1158             } else {
1159                 $imported = 0;
1160             }
1161         }
1162
1163         if(!$imported) {
1164             $logger->info("vl: record $rec_id was not imported");
1165             $$report_args{evt} = $e->event unless $$report_args{evt};
1166             $$report_args{no_import} = 1;
1167             finish_rec_import_attempt($report_args);
1168         }
1169     }
1170
1171     # see if we need to mark any queues as complete
1172     for my $q_id (keys %queues) {
1173
1174         my $e = new_editor(xact => 1);
1175         my $remaining = $e->$search_func(
1176             [{queue => $q_id, import_time => undef}, {limit =>1}], {idlist => 1});
1177
1178         unless(@$remaining) {
1179             my $queue = $e->$retrieve_queue_func($q_id);
1180             unless($U->is_true($queue->complete)) {
1181                 $queue->complete('t');
1182                 $e->$update_queue_func($queue) or return $e->die_event;
1183                 $e->commit;
1184                 next;
1185             }
1186         } 
1187         $e->rollback;
1188     }
1189
1190     # import the copies
1191     import_record_asset_list_impl($conn, \@success_rec_ids, $requestor) if @success_rec_ids;
1192
1193     $conn->respond({total => $$report_args{total}, progress => $$report_args{progress}});
1194     return undef;
1195 }
1196
1197
1198 sub try_auto_overlay {
1199     my $e = shift;
1200     my $type = shift;
1201     my $report_args = shift;
1202     my $overlay_func  = shift;
1203     my $retrieve_func = shift; 
1204     my $rec_class = shift;
1205     my $rec_id  = shift;
1206     my $match_quality_ratio = shift;
1207     my $merge_profile  = shift;
1208     my $ft_merge_profile = shift;
1209
1210     my $imported = 0;
1211     my $error = 0;
1212
1213     # Find the best match and overlay if the quality ratio allows it.
1214     my $res = $e->json_query(
1215         {
1216             from => [
1217                 $overlay_func,
1218                 $rec_id, 
1219                 $merge_profile,
1220                 $match_quality_ratio
1221             ]
1222         }
1223     );
1224
1225     if($res and ($res = $res->[0])) {
1226
1227         if($res->{$overlay_func} eq 't') {
1228
1229             # first attempt succeeded
1230             $imported = 1;
1231
1232         } else {
1233
1234             # quality-limited merge failed with insufficient quality.  If there is a 
1235             # fall-through merge profile, re-do the merge with the alternate profile
1236             # and no quality restriction.
1237
1238             if($ft_merge_profile and $match_quality_ratio > 0) {
1239
1240                 $logger->info("vl: $type auto-merge failed with profile $merge_profile; ".
1241                     "re-merging with fall-through profile $ft_merge_profile");
1242
1243                 my $res = $e->json_query(
1244                     {
1245                         from => [
1246                             $overlay_func,
1247                             $rec_id, 
1248                             $ft_merge_profile,
1249                             0 # minimum quality not required
1250                         ]
1251                     }
1252                 );
1253
1254                 if($res and ($res = $res->[0])) {
1255
1256                     if($res->{$overlay_func} eq 't') {
1257
1258                         # second attempt succeeded
1259                         $imported = 1;
1260
1261                     } else {
1262
1263                         # failed to merge on second attempt
1264                         $logger->info("vl: $type auto-merge with fall-through failed for queued rec $rec_id");
1265                     }
1266                 } else {
1267                     
1268                     # second attempt died 
1269                     $error = 1;
1270                     $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
1271                 }
1272
1273             } else { 
1274
1275                 # failed to merge on first attempt, no fall-through was provided
1276                 $$report_args{import_error} = 'overlay.record.quality' if $match_quality_ratio > 0;
1277                 $logger->info("vl: $type auto-merge failed for queued rec $rec_id");
1278             }
1279         }
1280
1281     } else {
1282
1283         # first attempt died 
1284         $error = 1;
1285         $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
1286     }
1287
1288     if($imported) {
1289
1290         # at least 1 of the attempts succeeded
1291         $logger->info("vl: $type auto-merge succeeded for queued rec $rec_id");
1292
1293         # re-fetch the record to pick up the imported_as value from the DB
1294         $$report_args{rec} = $e->$retrieve_func([
1295             $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1296     }
1297
1298     return ($imported, $error, $$report_args{rec});
1299 }
1300
1301
1302 # tracks any import errors, commits the current xact, responds to the client
1303 sub finish_rec_import_attempt {
1304     my $args = shift;
1305     my $evt = $$args{evt};
1306     my $rec = $$args{rec};
1307     my $e = $$args{e};
1308
1309     my $error = $$args{import_error};
1310     $error = 'general.unknown' if $evt and not $error;
1311
1312     # error tracking
1313     if($rec) {
1314
1315         if($error or $evt) {
1316             # failed import
1317             # since an error occurred, there's no guarantee the transaction wasn't 
1318             # rolled back.  force a rollback and create a new editor.
1319             $e->rollback;
1320             $e = new_editor(xact => 1);
1321             $rec->import_error($error);
1322
1323             if($evt) {
1324                 my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 140));
1325                 $rec->error_detail($detail);
1326             }
1327
1328             my $method = 'update_vandelay_queued_bib_record';
1329             $method =~ s/bib/authority/ if $$args{type} eq 'auth';
1330             $e->$method($rec) and $e->commit or $e->rollback;
1331
1332         } else {
1333             # commit the successful import
1334             $e->commit;
1335         }
1336
1337     } else {
1338         # requested queued record was not found
1339         $e->rollback;
1340     }
1341         
1342     # respond to client
1343     if($$args{report_all} or ($$args{progress} % $$args{step}) == 0) {
1344         $$args{conn}->respond({
1345             total => $$args{total}, 
1346             progress => $$args{progress}, 
1347             imported => ($rec) ? $rec->id : undef,
1348             import_error => $error,
1349             no_import => $$args{no_import},
1350             err_event => $evt
1351         });
1352         $$args{step} *= 2 unless $$args{step} == 256;
1353     }
1354
1355     $$args{progress}++;
1356 }
1357
1358
1359
1360
1361
1362 __PACKAGE__->register_method(  
1363     api_name    => "open-ils.vandelay.bib_queue.owner.retrieve",
1364     method      => 'owner_queue_retrieve',
1365     api_level   => 1,
1366     argc        => 2,
1367     stream      => 1,
1368     record_type => 'bib'
1369 );
1370 __PACKAGE__->register_method(  
1371     api_name    => "open-ils.vandelay.authority_queue.owner.retrieve",
1372     method      => 'owner_queue_retrieve',
1373     api_level   => 1,
1374     argc        => 2,
1375     stream      => 1,
1376     record_type => 'auth'
1377 );
1378
1379 sub owner_queue_retrieve {
1380     my($self, $conn, $auth, $owner_id, $filters) = @_;
1381     my $e = new_editor(authtoken => $auth, xact => 1);
1382     return $e->die_event unless $e->checkauth;
1383     $owner_id = $e->requestor->id; # XXX add support for viewing other's queues?
1384     my $queues;
1385     $filters ||= {};
1386     my $search = {owner => $owner_id};
1387     $search->{$_} = $filters->{$_} for keys %$filters;
1388
1389     if($self->{record_type} eq 'bib') {
1390         $queues = $e->search_vandelay_bib_queue(
1391             [$search, {order_by => {vbq => 'evergreen.lowercase(name)'}}]);
1392     } else {
1393         $queues = $e->search_vandelay_authority_queue(
1394             [$search, {order_by => {vaq => 'evergreen.lowercase(name)'}}]);
1395     }
1396     $conn->respond($_) for @$queues;
1397     $e->rollback;
1398     return undef;
1399 }
1400
1401 __PACKAGE__->register_method(  
1402     api_name    => "open-ils.vandelay.bib_queue.delete",
1403     method      => "delete_queue",
1404     api_level   => 1,
1405     argc        => 2,
1406     record_type => 'bib'
1407 );            
1408 __PACKAGE__->register_method(  
1409     api_name    => "open-ils.vandelay.auth_queue.delete",
1410     method      => "delete_queue",
1411     api_level   => 1,
1412     argc        => 2,
1413     record_type => 'auth'
1414 );  
1415
1416 sub delete_queue {
1417     my($self, $conn, $auth, $q_id) = @_;
1418     my $e = new_editor(xact => 1, authtoken => $auth);
1419     return $e->die_event unless $e->checkauth;
1420     if($self->{record_type} eq 'bib') {
1421         return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
1422         my $queue = $e->retrieve_vandelay_bib_queue($q_id)
1423             or return $e->die_event;
1424         $e->delete_vandelay_bib_queue($queue)
1425             or return $e->die_event;
1426     } else {
1427            return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
1428         my $queue = $e->retrieve_vandelay_authority_queue($q_id)
1429             or return $e->die_event;
1430         $e->delete_vandelay_authority_queue($queue)
1431             or return $e->die_event;
1432     }
1433     $e->commit;
1434     return 1;
1435 }
1436
1437
1438 __PACKAGE__->register_method(  
1439     api_name    => "open-ils.vandelay.queued_bib_record.html",
1440     method      => 'queued_record_html',
1441     api_level   => 1,
1442     argc        => 2,
1443     stream      => 1,
1444     record_type => 'bib'
1445 );
1446 __PACKAGE__->register_method(  
1447     api_name    => "open-ils.vandelay.queued_authority_record.html",
1448     method      => 'queued_record_html',
1449     api_level   => 1,
1450     argc        => 2,
1451     stream      => 1,
1452     record_type => 'auth'
1453 );
1454
1455 sub queued_record_html {
1456     my($self, $conn, $auth, $rec_id) = @_;
1457     my $e = new_editor(xact=>1,authtoken => $auth);
1458     return $e->die_event unless $e->checkauth;
1459     my $rec;
1460     if($self->{record_type} eq 'bib') {
1461         $rec = $e->retrieve_vandelay_queued_bib_record($rec_id)
1462             or return $e->die_event;
1463     } else {
1464         $rec = $e->retrieve_vandelay_queued_authority_record($rec_id)
1465             or return $e->die_event;
1466     }
1467
1468     $e->rollback;
1469     return $U->simplereq(
1470         'open-ils.search',
1471         'open-ils.search.biblio.record.html', undef, 1, $rec->marc);
1472 }
1473
1474
1475 __PACKAGE__->register_method(  
1476     api_name    => "open-ils.vandelay.bib_queue.summary.retrieve", 
1477     method      => 'retrieve_queue_summary',
1478     api_level   => 1,
1479     argc        => 2,
1480     stream      => 1,
1481     record_type => 'bib'
1482 );
1483 __PACKAGE__->register_method(  
1484     api_name    => "open-ils.vandelay.auth_queue.summary.retrieve",
1485     method      => 'retrieve_queue_summary',
1486     api_level   => 1,
1487     argc        => 2,
1488     stream      => 1,
1489     record_type => 'auth'
1490 );
1491
1492 sub retrieve_queue_summary {
1493     my($self, $conn, $auth, $queue_id) = @_;
1494     my $e = new_editor(xact=>1, authtoken => $auth);
1495     return $e->die_event unless $e->checkauth;
1496
1497     my $queue;
1498     my $type = $self->{record_type};
1499     if($type eq 'bib') {
1500         $queue = $e->retrieve_vandelay_bib_queue($queue_id)
1501             or return $e->die_event;
1502     } else {
1503         $queue = $e->retrieve_vandelay_authority_queue($queue_id)
1504             or return $e->die_event;
1505     }
1506
1507     my $evt = check_queue_perms($e, $type, $queue);
1508     return $evt if $evt;
1509
1510     my $search = 'search_vandelay_queued_bib_record';
1511     $search =~ s/bib/authority/ if $type ne 'bib';
1512
1513     my $summary = {
1514         queue => $queue,
1515         total => scalar(@{$e->$search({queue => $queue_id}, {idlist=>1})}),
1516         imported => scalar(@{$e->$search({queue => $queue_id, import_time => {'!=' => undef}}, {idlist=>1})}),
1517     };
1518
1519     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
1520     $summary->{rec_import_errors} = $e->json_query({
1521         select => {$class => [{alias => 'count', column => 'id', transform => 'count', aggregate => 1}]},
1522         from => $class,
1523         where => {queue => $queue_id, import_error => {'!=' => undef}}
1524     })->[0]->{count};
1525
1526     if($type eq 'bib') {
1527         
1528         # count of all items attached to records in the queue in question
1529         my $query = {
1530             select => {vii => [{alias => 'count', column => 'id', transform => 'count', aggregate => 1}]},
1531             from => 'vii',
1532             where => {
1533                 record => {
1534                     in => {
1535                         select => {vqbr => ['id']},
1536                         from => 'vqbr',
1537                         where => {queue => $queue_id}
1538                     }
1539                 }
1540             }
1541         };
1542         $summary->{total_items} = $e->json_query($query)->[0]->{count};
1543
1544         # count of items we attempted to import, but errored, attached to records in the queue in question
1545         $query->{where}->{import_error} = {'!=' => undef};
1546         $summary->{item_import_errors} = $e->json_query($query)->[0]->{count};
1547
1548         # count of items we successfully imported attached to records in the queue in question
1549         delete $query->{where}->{import_error};
1550         $query->{where}->{import_time} = {'!=' => undef};
1551         $summary->{total_items_imported} = $e->json_query($query)->[0]->{count};
1552     }
1553
1554     return $summary;
1555 }
1556
1557 # --------------------------------------------------------------------------------
1558 # Given a list of queued record IDs, imports all items attached to those records
1559 # --------------------------------------------------------------------------------
1560 sub import_record_asset_list_impl {
1561     my($conn, $rec_ids, $requestor) = @_;
1562
1563     my $roe = new_editor(xact=> 1, requestor => $requestor);
1564
1565     # for speed, filter out any records have not been 
1566     # imported or have no import items to load
1567     $rec_ids = $roe->json_query({
1568         select => {vqbr => ['id']},
1569         from => {vqbr => 'vii'},
1570         where => {'+vqbr' => {
1571             id => $rec_ids,
1572             import_time => {'!=' => undef}
1573         }},
1574         distinct => 1
1575     });
1576     $rec_ids = [map {$_->{id}} @$rec_ids];
1577
1578     my $report_args = {
1579         conn => $conn,
1580         total => scalar(@$rec_ids),
1581         step => 1, # how often to respond
1582         progress => 1,
1583         in_count => 0,
1584     };
1585
1586     for my $rec_id (@$rec_ids) {
1587         my $rec = $roe->retrieve_vandelay_queued_bib_record($rec_id);
1588         my $item_ids = $roe->search_vandelay_import_item(
1589             {record => $rec->id, import_error => undef}, 
1590             {idlist=>1}
1591         );
1592
1593         for my $item_id (@$item_ids) {
1594             my $e = new_editor(requestor => $requestor, xact => 1);
1595             my $item = $e->retrieve_vandelay_import_item($item_id);
1596             my ($copy, $vol, $evt);
1597
1598             $$report_args{import_item} = $item;
1599             $$report_args{e} = $e;
1600             $$report_args{import_error} = undef;
1601             $$report_args{evt} = undef;
1602
1603             if (my $copy_id = $item->internal_id) { # assignment
1604                 # copy matches an existing copy.  Overlay instead of create.
1605
1606                 $logger->info("vl: performing copy overlay for internal_id=$copy_id");
1607
1608                 my $qt = $e->json_query({
1609                     select => {vbq => ['queue_type']},
1610                     from => {vqbr => 'vbq'},
1611                     where => {'+vqbr' => {id => $rec_id}}
1612                 })->[0]->{queue_type};
1613
1614                 if ($qt eq 'acq') {
1615                     # internal_id for ACQ queues refers to acq.lineitem_detail.id
1616                     # pull the real copy id from the acq LID
1617
1618                     my $lid = $e->retrieve_acq_lineitem_detail($copy_id);
1619                     if (!$lid) {
1620                         $$report_args{evt} = $e->die_event;
1621                         respond_with_status($report_args);
1622                         next;
1623                     }
1624                     $copy_id = $lid->eg_copy_id;
1625                     $logger->info("vl: performing ACQ copy overlay for copy $copy_id");
1626                 }
1627
1628                 $copy = $e->search_asset_copy([
1629                     {id => $copy_id, deleted => 'f'},
1630                     {flesh => 1, flesh_fields => {acp => ['call_number']}}
1631                 ])->[0];
1632
1633                 if (!$copy) {
1634                     $$report_args{evt} = $e->die_event;
1635                     respond_with_status($report_args);
1636                     next;
1637                 }
1638
1639                 # prevent update of unrelated copies
1640                 if ($copy->call_number->record != $rec->imported_as) {
1641                     $logger->info("vl: attempt to overlay unrelated copy=$copy_id; rec=".$rec->imported_as);
1642
1643                     $evt = OpenILS::Event->new('INVALID_IMPORT_COPY_ID', 
1644                         note => 'Cannot overlay copies for unlinked bib',
1645                         bre => $rec->imported_as, 
1646                         copy_id => $copy_id
1647                     );
1648                     $$report_args{evt} = $evt;
1649                     respond_with_status($report_args);
1650                     next;
1651                 }
1652
1653                 # overlaying copies requires an extra permission
1654                 if (!$e->allowed("IMPORT_OVERLAY_COPY", $copy->call_number->owning_lib)) {
1655                     $$report_args{evt} = $e->die_event;
1656                     respond_with_status($report_args);
1657                     next;
1658                 }
1659
1660                 # are we updating the call-number?
1661                 if ($item->call_number and $item->call_number ne $copy->call_number->label) {
1662
1663                     my $count = $e->json_query({
1664                         select => {acp => [{
1665                             alias => 'count', 
1666                             column => 'id', 
1667                             transform => 'count', 
1668                             aggregate => 1
1669                         }]},
1670                         from => 'acp',
1671                         where => {
1672                             deleted => 'f',
1673                             call_number => $copy->call_number->id
1674                         }
1675                     })->[0]->{count};
1676
1677                     if ($count == 1) {
1678                         # if this is the only copy attached to this 
1679                         # callnumber, just update the callnumber
1680
1681                         $logger->info("vl: updating callnumber label in copy overlay");
1682
1683                         $copy->call_number->label($item->call_number);
1684                         if (!$e->update_asset_call_number($copy->call_number)) {
1685                             $$report_args{evt} = $e->die_event;
1686                             respond_with_status($report_args);
1687                             next;
1688                         }
1689
1690                     } else {
1691
1692                         # otherwise, move the copy to a new/existing 
1693                         # call-number with the given label/owner
1694                         # note that overlay does not allow the owning_lib 
1695                         # to be changed.  Should it?
1696
1697                         $logger->info("vl: moving copy to new callnumber in copy overlay");
1698
1699                         ($vol, $evt) =
1700                             OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1701                                 $e, $item->call_number, 
1702                                 $copy->call_number->record, 
1703                                 $copy->call_number->owning_lib
1704                             );
1705
1706                         if($evt) {
1707                             $$report_args{evt} = $evt;
1708                             respond_with_status($report_args);
1709                             next;
1710                         }
1711
1712                         $copy->call_number($vol);
1713                     }
1714                 } # cn-update
1715
1716                 # for every field that has a non-'' value, overlay the copy value
1717                 foreach (qw/ barcode location circ_lib status 
1718                     circulate deposit deposit_amount ref holdable 
1719                     price circ_as_type alert_message opac_visible circ_modifier/) {
1720
1721                     my $val = $item->$_();
1722                     $copy->$_($val) if $val and $val ne '';
1723                 }
1724
1725                 # de-flesh for update
1726                 $copy->call_number($copy->call_number->id);
1727                 $copy->ischanged(1);
1728
1729                 $evt = OpenILS::Application::Cat::AssetCommon->
1730                     update_fleshed_copies($e, {all => 1}, undef, [$copy]);
1731
1732                 if($evt) {
1733                     $$report_args{evt} = $evt;
1734                     respond_with_status($report_args);
1735                     next;
1736                 }
1737
1738             } else { 
1739
1740                 # Creating a new copy
1741                 $logger->info("vl: creating new copy in import");
1742
1743                 # --------------------------------------------------------------------------------
1744                 # Find or create the volume
1745                 # --------------------------------------------------------------------------------
1746                 my ($vol, $evt) =
1747                     OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1748                         $e, $item->call_number, $rec->imported_as, $item->owning_lib);
1749
1750                 if($evt) {
1751                     $$report_args{evt} = $evt;
1752                     respond_with_status($report_args);
1753                     next;
1754                 }
1755
1756                 # --------------------------------------------------------------------------------
1757                 # Create the new copy
1758                 # --------------------------------------------------------------------------------
1759                 $copy = Fieldmapper::asset::copy->new;
1760                 $copy->loan_duration(2);
1761                 $copy->fine_level(2);
1762                 $copy->barcode($item->barcode);
1763                 $copy->location($item->location);
1764                 $copy->circ_lib($item->circ_lib || $item->owning_lib);
1765                 $copy->status( defined($item->status) ? $item->status : OILS_COPY_STATUS_IN_PROCESS );
1766                 $copy->circulate($item->circulate);
1767                 $copy->deposit($item->deposit);
1768                 $copy->deposit_amount($item->deposit_amount);
1769                 $copy->ref($item->ref);
1770                 $copy->holdable($item->holdable);
1771                 $copy->price($item->price);
1772                 $copy->circ_as_type($item->circ_as_type);
1773                 $copy->alert_message($item->alert_message);
1774                 $copy->opac_visible($item->opac_visible);
1775                 $copy->circ_modifier($item->circ_modifier);
1776
1777                 # --------------------------------------------------------------------------------
1778                 # Check for dupe barcode
1779                 # --------------------------------------------------------------------------------
1780                 if($evt = OpenILS::Application::Cat::AssetCommon->create_copy($e, $vol, $copy)) {
1781                     $$report_args{evt} = $evt;
1782                     $$report_args{import_error} = 'import.item.duplicate.barcode'
1783                         if $evt->{textcode} eq 'ITEM_BARCODE_EXISTS';
1784                     respond_with_status($report_args);
1785                     next;
1786                 }
1787
1788                 # --------------------------------------------------------------------------------
1789                 # create copy notes
1790                 # --------------------------------------------------------------------------------
1791                 $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1792                     $e, $copy, '', $item->pub_note, 1) if $item->pub_note;
1793
1794                 if($evt) {
1795                     $$report_args{evt} = $evt;
1796                     respond_with_status($report_args);
1797                     next;
1798                 }
1799
1800                 $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1801                     $e, $copy, '', $item->priv_note) if $item->priv_note;
1802
1803                 if($evt) {
1804                     $$report_args{evt} = $evt;
1805                     respond_with_status($report_args);
1806                     next;
1807                 }
1808             }
1809
1810             # set the import data on the import item
1811             $item->imported_as($copy->id); # $copy->id is set by create_copy() ^--
1812             $item->import_time('now');
1813
1814             unless($e->update_vandelay_import_item($item)) {
1815                 $$report_args{evt} = $e->die_event;
1816                 respond_with_status($report_args);
1817                 next;
1818             }
1819
1820             # --------------------------------------------------------------------------------
1821             # Item import succeeded
1822             # --------------------------------------------------------------------------------
1823             $e->commit;
1824             $$report_args{in_count}++;
1825             respond_with_status($report_args);
1826             $logger->info("vl: successfully imported item " . $item->barcode);
1827         }
1828     }
1829
1830     $roe->rollback;
1831     return undef;
1832 }
1833
1834
1835 sub respond_with_status {
1836     my $args = shift;
1837     my $e = $$args{e};
1838
1839     #  If the import failed, track the failure reason
1840
1841     my $error = $$args{import_error};
1842     my $evt = $$args{evt};
1843
1844     if($error or $evt) {
1845
1846         my $item = $$args{import_item};
1847         $logger->info("vl: unable to import item " . $item->barcode);
1848
1849         $error ||= 'general.unknown';
1850         $item->import_error($error);
1851
1852         if($evt) {
1853             my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 140));
1854             $item->error_detail($detail);
1855         }
1856
1857         # state of the editor is unknown at this point.  Force a rollback and start over.
1858         $e->rollback;
1859         $e = new_editor(xact => 1);
1860         $e->update_vandelay_import_item($item);
1861         $e->commit;
1862     }
1863
1864     if($$args{report_all} or ($$args{progress} % $$args{step}) == 0) {
1865         $$args{conn}->respond({
1866             total => $$args{total},
1867             progress => $$args{progress},
1868             success_count => $$args{success_count},
1869             err_event => $evt
1870         });
1871         $$args{step} *= 2 unless $$args{step} == 256;
1872     }
1873
1874     $$args{progress}++;
1875 }
1876
1877 __PACKAGE__->register_method(  
1878     api_name    => "open-ils.vandelay.match_set.get_tree",
1879     method      => "match_set_get_tree",
1880     api_level   => 1,
1881     argc        => 2,
1882     signature   => {
1883         desc    => q/For a given vms object, return a tree of match set points
1884                     represented by a vmsp object with recursively fleshed
1885                     children./
1886     }
1887 );
1888
1889 sub match_set_get_tree {
1890     my ($self, $conn, $authtoken, $match_set_id) = @_;
1891
1892     $match_set_id = int($match_set_id) or return;
1893
1894     my $e = new_editor("authtoken" => $authtoken);
1895     $e->checkauth or return $e->die_event;
1896
1897     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1898         return $e->die_event;
1899
1900     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1901         return $e->die_event;
1902
1903     my $tree = $e->search_vandelay_match_set_point([
1904         {"match_set" => $match_set_id, "parent" => undef},
1905         {"flesh" => -1, "flesh_fields" => {"vmsp" => ["children"]}}
1906     ]) or return $e->die_event;
1907
1908     return pop @$tree;
1909 }
1910
1911
1912 __PACKAGE__->register_method(
1913     api_name    => "open-ils.vandelay.match_set.update",
1914     method      => "match_set_update_tree",
1915     api_level   => 1,
1916     argc        => 3,
1917     signature   => {
1918         desc => q/Replace any vmsp objects associated with a given (by ID) vms
1919                 with the given objects (recursively fleshed vmsp tree)./
1920     }
1921 );
1922
1923 sub _walk_new_vmsp {
1924     my ($e, $match_set_id, $node, $parent_id) = @_;
1925
1926     my $point = new Fieldmapper::vandelay::match_set_point;
1927     $point->parent($parent_id);
1928     $point->match_set($match_set_id);
1929     $point->$_($node->$_) for (qw/bool_op svf tag subfield negate quality/);
1930
1931     $e->create_vandelay_match_set_point($point) or return $e->die_event;
1932
1933     $parent_id = $e->data->id;
1934     if ($node->children && @{$node->children}) {
1935         for (@{$node->children}) {
1936             return $e->die_event if
1937                 _walk_new_vmsp($e, $match_set_id, $_, $parent_id);
1938         }
1939     }
1940
1941     return;
1942 }
1943
1944 sub match_set_update_tree {
1945     my ($self, $conn, $authtoken, $match_set_id, $tree) = @_;
1946
1947     my $e = new_editor("xact" => 1, "authtoken" => $authtoken);
1948     $e->checkauth or return $e->die_event;
1949
1950     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1951         return $e->die_event;
1952
1953     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1954         return $e->die_event;
1955
1956     my $existing = $e->search_vandelay_match_set_point([
1957         {"match_set" => $match_set_id},
1958         {"order_by" => {"vmsp" => "id DESC"}}
1959     ]) or return $e->die_event;
1960
1961     # delete points, working up from leaf points to the root
1962     while(@$existing) {
1963         for my $point (shift @$existing) {
1964             if( grep {$_->parent eq $point->id} @$existing) {
1965                 push(@$existing, $point);
1966             } else {
1967                 $e->delete_vandelay_match_set_point($point) or return $e->die_event;
1968             }
1969         }
1970     }
1971
1972     _walk_new_vmsp($e, $match_set_id, $tree);
1973
1974     $e->commit or return $e->die_event;
1975 }
1976
1977 __PACKAGE__->register_method(  
1978     api_name    => 'open-ils.vandelay.bib_queue.to_bucket',
1979     method      => 'bib_queue_to_bucket',
1980     api_level   => 1,
1981     argc        => 2,
1982     signature   => {
1983         desc    => q/Add to or create a new bib container (bucket) with the successfully 
1984                     imported contents of a vandelay queue.  Any user that has Vandelay 
1985                     queue create permissions can append or create buckets from his-her own queues./,
1986         params  => [
1987             {desc => 'Authtoken', type => 'string'},
1988             {desc => 'Queue ID', type => 'number'},
1989             {desc => 'Bucket Name', type => 'string'}
1990         ],
1991         return  => {desc => q/
1992             {bucket => $bucket, addcount => number-of-items-added-to-bucket, item_count => total-bucket-item-count} on success,
1993             {add_count => 0} if there is nothing to do, and Event on error/}
1994     }
1995 );
1996
1997 sub bib_queue_to_bucket {
1998     my ($self, $conn, $auth, $q_id, $bucket_name) = @_;
1999
2000     my $e = new_editor(xact => 1, authtoken => $auth);
2001     return $e->die_event unless $e->checkauth;
2002     
2003     my $queue = $e->retrieve_vandelay_bib_queue($q_id)
2004         or return $e->die_event;
2005
2006     return OpenILS::Event->new('BAD_PARAMS', 
2007         note => q/Bucket creator must be queue owner/)
2008         unless $queue->owner == $e->requestor->id;
2009
2010     # find the bib IDs that will go into the bucket
2011     my $bib_ids = $e->json_query({
2012         select => {vqbr => ['imported_as']},
2013         from => 'vqbr',
2014         where => {queue => $q_id, imported_as => {'!=' => undef}}
2015     });
2016
2017     if (!@$bib_ids) { # no records to add
2018         $e->rollback;
2019         return {add_count => 0};
2020     }
2021
2022     # allow user to add to an existing bucket by name
2023     my $bucket = $e->search_container_biblio_record_entry_bucket({
2024         owner => $e->requestor->id, 
2025         name => $bucket_name,
2026         btype => 'vandelay_queue'
2027     })->[0];
2028
2029     # if the bucket does not exist, create a new one
2030     if (!$bucket) { 
2031         $bucket = Fieldmapper::container::biblio_record_entry_bucket->new;
2032         $bucket->name($bucket_name);
2033         $bucket->owner($e->requestor->id);
2034         $bucket->btype('vandelay_queue');
2035
2036         $e->create_container_biblio_record_entry_bucket($bucket)
2037             or return $e->die_event;
2038     }
2039
2040     # create the new bucket items
2041     for my $bib_id ( map {$_->{imported_as}} @$bib_ids ) {
2042         my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2043         $item->target_biblio_record_entry($bib_id);
2044         $item->bucket($bucket->id);
2045         $e->create_container_biblio_record_entry_bucket_item($item)
2046             or return $e->die_event;
2047     }
2048
2049     # re-fetch the bucket to pick up the correct create_time
2050     $bucket = $e->retrieve_container_biblio_record_entry_bucket($bucket->id)
2051         or return $e->die_event;
2052
2053     # get the total count of items in this bucket
2054     my $count = $e->json_query({
2055         select => {cbrebi => [{
2056             aggregate =>  1,
2057             transform => 'count',
2058             alias => 'count',
2059             column => 'id'
2060         }]},
2061         from => 'cbrebi',
2062         where => {bucket => $bucket->id}
2063     })->[0];
2064
2065     $e->commit;
2066
2067     return {
2068         bucket => $bucket, 
2069         add_count => scalar(@$bib_ids), # items added to the bucket
2070         item_count => $count->{count} # total items in buckets
2071     };
2072 }
2073
2074 1;