]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Vandelay.pm
Strip configured fields during import/overlay II
[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     my $strip_grps = $$args{strip_field_groups}; # bib-only
890
891     my $overlay_func = 'vandelay.overlay_bib_record';
892     my $auto_overlay_func = 'vandelay.auto_overlay_bib_record';
893     my $auto_overlay_best_func = 'vandelay.auto_overlay_bib_record_with_best'; # XXX bib-only
894     my $retrieve_func = 'retrieve_vandelay_queued_bib_record';
895     my $update_func = 'update_vandelay_queued_bib_record';
896     my $search_func = 'search_vandelay_queued_bib_record';
897     my $retrieve_queue_func = 'retrieve_vandelay_bib_queue';
898     my $update_queue_func = 'update_vandelay_bib_queue';
899     my $delete_queue_func = 'delete_vandelay_bib_queue';
900     my $rec_class = 'vqbr';
901
902     my $editor = new_editor();
903
904     my %bib_sources;
905     my $sources = $editor->search_config_bib_source({id => {'!=' => undef}});
906     $bib_sources{$_->id} = $_->source for @$sources;
907
908     if($type eq 'auth') {
909         $overlay_func =~ s/bib/auth/o;
910         $auto_overlay_func = s/bib/auth/o;
911         $retrieve_func =~ s/bib/authority/o;
912         $retrieve_queue_func =~ s/bib/authority/o;
913         $update_queue_func =~ s/bib/authority/o;
914         $update_func =~ s/bib/authority/o;
915         $search_func =~ s/bib/authority/o;
916         $delete_queue_func =~ s/bib/authority/o;
917         $rec_class = 'vqar';
918     }
919
920     my $new_rec_perm_cache;
921     my @success_rec_ids;
922     for my $rec_id (@$rec_ids) {
923
924         my $error = 0;
925         my $overlay_target = $overlay_map->{$rec_id};
926
927         my $e = new_editor(xact => 1);
928         $e->requestor($requestor);
929
930         $$report_args{e} = $e;
931         $$report_args{evt} = undef;
932         $$report_args{import_error} = undef;
933         $$report_args{no_import} = 0;
934
935         my $rec = $e->$retrieve_func([
936             $rec_id,
937             {   flesh => 1,
938                 flesh_fields => { $rec_class => ['matches']},
939             }
940         ]);
941
942         unless($rec) {
943             $$report_args{evt} = $e->event;
944             finish_rec_import_attempt($report_args);
945             next;
946         }
947
948         if($rec->import_time) {
949             # if the record is already imported, that means it may have 
950             # un-imported copies.  Add to success list for later processing.
951             push(@success_rec_ids, $rec_id);
952             $e->rollback;
953             next;
954         }
955
956         $$report_args{rec} = $rec;
957         $queues{$rec->queue} = 1;
958
959         my $record;
960         my $imported = 0;
961
962         if ($type eq 'bib') {
963             # strip configured / selected MARC tags from inbound records
964
965             my $marcdoc = XML::LibXML->new->parse_string($rec->marc);
966             $rec->marc($U->strip_marc_fields($e, $marcdoc, $strip_grps));
967
968             unless ($e->$update_func($rec)) {
969                 $$report_args{evt} = $e->die_event;
970                 finish_rec_import_attempt($report_args);
971                 next;
972             }
973         }
974
975         if(defined $overlay_target) {
976             # Caller chose an explicit overlay target
977
978             my $res = $e->json_query(
979                 {
980                     from => [
981                         $overlay_func,
982                         $rec_id,
983                         $overlay_target, 
984                         $merge_profile
985                     ]
986                 }
987             );
988
989             if($res and ($res = $res->[0])) {
990
991                 if($res->{$overlay_func} eq 't') {
992                     $logger->info("vl: $type direct overlay succeeded for queued rec ".
993                         "$rec_id and overlay target $overlay_target");
994                     $imported = 1;
995                 }
996
997             } else {
998                 $error = 1;
999                 $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
1000             }
1001
1002         } else {
1003
1004             if($auto_overlay_1match) { # overlay if there is exactly 1 match
1005
1006                 my %match_recs = map { $_->eg_record => 1 } @{$rec->matches};
1007
1008                 if( scalar(keys %match_recs) == 1) { # all matches point to the same record
1009
1010                     ($imported, $error, $rec) = try_auto_overlay(
1011                         $e, $type,
1012                         $report_args, 
1013                         $auto_overlay_best_func,
1014                         $retrieve_func,
1015                         $rec_class,
1016                         $rec_id, 
1017                         $match_quality_ratio, 
1018                         $merge_profile, 
1019                         $ft_merge_profile
1020                     );
1021                 }
1022             }
1023
1024             if(!$imported and !$error and $auto_overlay_exact and scalar(@{$rec->matches}) == 1 ) {
1025                 
1026                 # caller says to overlay if there is an /exact/ match
1027                 # $auto_overlay_func only proceeds and returns true on exact matches
1028
1029                 my $res = $e->json_query(
1030                     {
1031                         from => [
1032                             $auto_overlay_func,
1033                             $rec_id,
1034                             $merge_profile
1035                         ]
1036                     }
1037                 );
1038
1039                 if($res and ($res = $res->[0])) {
1040
1041                     if($res->{$auto_overlay_func} eq 't') {
1042                         $logger->info("vl: $type auto-overlay succeeded for queued rec $rec_id");
1043                         $imported = 1;
1044
1045                         # re-fetch the record to pick up the imported_as value from the DB
1046                         $$report_args{rec} = $rec = $e->$retrieve_func([
1047                             $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1048
1049                     } else {
1050                         $logger->info("vl: $type auto-overlay failed for queued rec $rec_id");
1051                     }
1052
1053                 } else {
1054                     $error = 1;
1055                     $logger->error("vl: Error attempting overlay with func=$auto_overlay_func, profile=$merge_profile, record=$rec_id");
1056                 }
1057             }
1058
1059             if(!$imported and !$error and $auto_overlay_best and scalar(@{$rec->matches}) > 0 ) {
1060                 # caller says to overlay the best match
1061
1062                 ($imported, $error, $rec) = try_auto_overlay(
1063                     $e, $type,
1064                     $report_args, 
1065                     $auto_overlay_best_func,
1066                     $retrieve_func,
1067                     $rec_class,
1068                     $rec_id, 
1069                     $match_quality_ratio, 
1070                     $merge_profile, 
1071                     $ft_merge_profile
1072                 );
1073             }
1074
1075             if(!$imported and !$error and $import_no_match and scalar(@{$rec->matches}) == 0) {
1076             
1077                 # No overlay / merge occurred.  Do a traditional record import by creating a new record
1078
1079                 if (!$new_rec_perm_cache) {
1080                     $new_rec_perm_cache = {};
1081
1082                     # all users creating new records are required to have the basic permission.
1083                     # if the client requests, we can enforce extra permissions for creating new records.
1084                     # for speed, check the permissions the first time then cache the result.
1085
1086                     my $perm = ($type eq 'bib') ? 'IMPORT_MARC' : 'IMPORT_AUTHORITY_MARC';
1087                     my $xperm = $$args{new_rec_perm};
1088                     my $rec_ou = $e->requestor->ws_ou;
1089
1090                     $new_rec_perm_cache->{evt} = $e->die_event
1091                         if !$e->allowed($perm, $rec_ou) || ($xperm and !$e->allowed($xperm, $rec_ou));
1092                 }
1093
1094                 if ($new_rec_perm_cache->{evt}) {
1095
1096                     # a cached event won't roll back the transaction (a la die_event), but
1097                     # the transaction will get rolled back in finish_rec_import_attempt() below
1098                     $$report_args{evt} = $new_rec_perm_cache->{evt};
1099                     $$report_args{import_error} = 'import.record.perm_failure';
1100
1101                 } else { # perm checks succeeded
1102
1103                     $logger->info("vl: creating new $type record for queued record $rec_id");
1104
1105                     if ($type eq 'bib') {
1106
1107                         $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
1108                             $e, $rec->marc, $bib_sources{$rec->bib_source}, undef, 1);
1109
1110                     } else { # authority record
1111
1112                         $record = OpenILS::Application::Cat::AuthCommon->import_authority_record($e, $rec->marc); #$source);
1113                     }
1114
1115                     if($U->event_code($record)) {
1116                         $$report_args{import_error} = 'import.duplicate.tcn' 
1117                             if $record->{textcode} eq 'OPEN_TCN_NOT_FOUND';
1118                         $$report_args{evt} = $record;
1119
1120                     } else {
1121
1122                         $logger->info("vl: successfully imported new $type record");
1123                         $rec->imported_as($record->id);
1124                         $imported = 1;
1125                     }
1126                 }
1127             }
1128         }
1129
1130         if($imported) {
1131
1132             $rec->import_time('now');
1133             $rec->clear_import_error;
1134             $rec->clear_error_detail;
1135
1136             if($e->$update_func($rec)) {
1137
1138                 if($type eq 'bib') {
1139
1140                     # see if this record is linked from an acq record.
1141                     my $li = $e->search_acq_lineitem(
1142                         {queued_record => $rec->id, state => {'!=' => 'canceled'}})->[0];
1143
1144                     if ($li) { 
1145                         # if so, update the acq lineitem to point to the imported record
1146                         $li->eg_bib_id($rec->imported_as);
1147                         $$report_args{evt} = $e->die_event unless $e->update_acq_lineitem($li);
1148                     }
1149                 }
1150
1151                 push @success_rec_ids, $rec_id;
1152                 finish_rec_import_attempt($report_args);
1153
1154             } else {
1155                 $imported = 0;
1156             }
1157         }
1158
1159         if(!$imported) {
1160             $logger->info("vl: record $rec_id was not imported");
1161             $$report_args{evt} = $e->event unless $$report_args{evt};
1162             $$report_args{no_import} = 1;
1163             finish_rec_import_attempt($report_args);
1164         }
1165     }
1166
1167     # see if we need to mark any queues as complete
1168     for my $q_id (keys %queues) {
1169
1170         my $e = new_editor(xact => 1);
1171         my $remaining = $e->$search_func(
1172             [{queue => $q_id, import_time => undef}, {limit =>1}], {idlist => 1});
1173
1174         unless(@$remaining) {
1175             my $queue = $e->$retrieve_queue_func($q_id);
1176             unless($U->is_true($queue->complete)) {
1177                 $queue->complete('t');
1178                 $e->$update_queue_func($queue) or return $e->die_event;
1179                 $e->commit;
1180                 next;
1181             }
1182         } 
1183         $e->rollback;
1184     }
1185
1186     # import the copies
1187     import_record_asset_list_impl($conn, \@success_rec_ids, $requestor) if @success_rec_ids;
1188
1189     $conn->respond({total => $$report_args{total}, progress => $$report_args{progress}});
1190     return undef;
1191 }
1192
1193
1194 sub try_auto_overlay {
1195     my $e = shift;
1196     my $type = shift;
1197     my $report_args = shift;
1198     my $overlay_func  = shift;
1199     my $retrieve_func = shift; 
1200     my $rec_class = shift;
1201     my $rec_id  = shift;
1202     my $match_quality_ratio = shift;
1203     my $merge_profile  = shift;
1204     my $ft_merge_profile = shift;
1205
1206     my $imported = 0;
1207     my $error = 0;
1208
1209     # Find the best match and overlay if the quality ratio allows it.
1210     my $res = $e->json_query(
1211         {
1212             from => [
1213                 $overlay_func,
1214                 $rec_id, 
1215                 $merge_profile,
1216                 $match_quality_ratio
1217             ]
1218         }
1219     );
1220
1221     if($res and ($res = $res->[0])) {
1222
1223         if($res->{$overlay_func} eq 't') {
1224
1225             # first attempt succeeded
1226             $imported = 1;
1227
1228         } else {
1229
1230             # quality-limited merge failed with insufficient quality.  If there is a 
1231             # fall-through merge profile, re-do the merge with the alternate profile
1232             # and no quality restriction.
1233
1234             if($ft_merge_profile and $match_quality_ratio > 0) {
1235
1236                 $logger->info("vl: $type auto-merge failed with profile $merge_profile; ".
1237                     "re-merging with fall-through profile $ft_merge_profile");
1238
1239                 my $res = $e->json_query(
1240                     {
1241                         from => [
1242                             $overlay_func,
1243                             $rec_id, 
1244                             $ft_merge_profile,
1245                             0 # minimum quality not required
1246                         ]
1247                     }
1248                 );
1249
1250                 if($res and ($res = $res->[0])) {
1251
1252                     if($res->{$overlay_func} eq 't') {
1253
1254                         # second attempt succeeded
1255                         $imported = 1;
1256
1257                     } else {
1258
1259                         # failed to merge on second attempt
1260                         $logger->info("vl: $type auto-merge with fall-through failed for queued rec $rec_id");
1261                     }
1262                 } else {
1263                     
1264                     # second attempt died 
1265                     $error = 1;
1266                     $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
1267                 }
1268
1269             } else { 
1270
1271                 # failed to merge on first attempt, no fall-through was provided
1272                 $$report_args{import_error} = 'overlay.record.quality' if $match_quality_ratio > 0;
1273                 $logger->info("vl: $type auto-merge failed for queued rec $rec_id");
1274             }
1275         }
1276
1277     } else {
1278
1279         # first attempt died 
1280         $error = 1;
1281         $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
1282     }
1283
1284     if($imported) {
1285
1286         # at least 1 of the attempts succeeded
1287         $logger->info("vl: $type auto-merge succeeded for queued rec $rec_id");
1288
1289         # re-fetch the record to pick up the imported_as value from the DB
1290         $$report_args{rec} = $e->$retrieve_func([
1291             $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1292     }
1293
1294     return ($imported, $error, $$report_args{rec});
1295 }
1296
1297
1298 # tracks any import errors, commits the current xact, responds to the client
1299 sub finish_rec_import_attempt {
1300     my $args = shift;
1301     my $evt = $$args{evt};
1302     my $rec = $$args{rec};
1303     my $e = $$args{e};
1304
1305     my $error = $$args{import_error};
1306     $error = 'general.unknown' if $evt and not $error;
1307
1308     # error tracking
1309     if($rec) {
1310
1311         if($error or $evt) {
1312             # failed import
1313             # since an error occurred, there's no guarantee the transaction wasn't 
1314             # rolled back.  force a rollback and create a new editor.
1315             $e->rollback;
1316             $e = new_editor(xact => 1);
1317             $rec->import_error($error);
1318
1319             if($evt) {
1320                 my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 140));
1321                 $rec->error_detail($detail);
1322             }
1323
1324             my $method = 'update_vandelay_queued_bib_record';
1325             $method =~ s/bib/authority/ if $$args{type} eq 'auth';
1326             $e->$method($rec) and $e->commit or $e->rollback;
1327
1328         } else {
1329             # commit the successful import
1330             $e->commit;
1331         }
1332
1333     } else {
1334         # requested queued record was not found
1335         $e->rollback;
1336     }
1337         
1338     # respond to client
1339     if($$args{report_all} or ($$args{progress} % $$args{step}) == 0) {
1340         $$args{conn}->respond({
1341             total => $$args{total}, 
1342             progress => $$args{progress}, 
1343             imported => ($rec) ? $rec->id : undef,
1344             import_error => $error,
1345             no_import => $$args{no_import},
1346             err_event => $evt
1347         });
1348         $$args{step} *= 2 unless $$args{step} == 256;
1349     }
1350
1351     $$args{progress}++;
1352 }
1353
1354
1355
1356
1357
1358 __PACKAGE__->register_method(  
1359     api_name    => "open-ils.vandelay.bib_queue.owner.retrieve",
1360     method      => 'owner_queue_retrieve',
1361     api_level   => 1,
1362     argc        => 2,
1363     stream      => 1,
1364     record_type => 'bib'
1365 );
1366 __PACKAGE__->register_method(  
1367     api_name    => "open-ils.vandelay.authority_queue.owner.retrieve",
1368     method      => 'owner_queue_retrieve',
1369     api_level   => 1,
1370     argc        => 2,
1371     stream      => 1,
1372     record_type => 'auth'
1373 );
1374
1375 sub owner_queue_retrieve {
1376     my($self, $conn, $auth, $owner_id, $filters) = @_;
1377     my $e = new_editor(authtoken => $auth, xact => 1);
1378     return $e->die_event unless $e->checkauth;
1379     $owner_id = $e->requestor->id; # XXX add support for viewing other's queues?
1380     my $queues;
1381     $filters ||= {};
1382     my $search = {owner => $owner_id};
1383     $search->{$_} = $filters->{$_} for keys %$filters;
1384
1385     if($self->{record_type} eq 'bib') {
1386         $queues = $e->search_vandelay_bib_queue(
1387             [$search, {order_by => {vbq => 'evergreen.lowercase(name)'}}]);
1388     } else {
1389         $queues = $e->search_vandelay_authority_queue(
1390             [$search, {order_by => {vaq => 'evergreen.lowercase(name)'}}]);
1391     }
1392     $conn->respond($_) for @$queues;
1393     $e->rollback;
1394     return undef;
1395 }
1396
1397 __PACKAGE__->register_method(  
1398     api_name    => "open-ils.vandelay.bib_queue.delete",
1399     method      => "delete_queue",
1400     api_level   => 1,
1401     argc        => 2,
1402     record_type => 'bib'
1403 );            
1404 __PACKAGE__->register_method(  
1405     api_name    => "open-ils.vandelay.auth_queue.delete",
1406     method      => "delete_queue",
1407     api_level   => 1,
1408     argc        => 2,
1409     record_type => 'auth'
1410 );  
1411
1412 sub delete_queue {
1413     my($self, $conn, $auth, $q_id) = @_;
1414     my $e = new_editor(xact => 1, authtoken => $auth);
1415     return $e->die_event unless $e->checkauth;
1416     if($self->{record_type} eq 'bib') {
1417         return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
1418         my $queue = $e->retrieve_vandelay_bib_queue($q_id)
1419             or return $e->die_event;
1420         $e->delete_vandelay_bib_queue($queue)
1421             or return $e->die_event;
1422     } else {
1423            return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
1424         my $queue = $e->retrieve_vandelay_authority_queue($q_id)
1425             or return $e->die_event;
1426         $e->delete_vandelay_authority_queue($queue)
1427             or return $e->die_event;
1428     }
1429     $e->commit;
1430     return 1;
1431 }
1432
1433
1434 __PACKAGE__->register_method(  
1435     api_name    => "open-ils.vandelay.queued_bib_record.html",
1436     method      => 'queued_record_html',
1437     api_level   => 1,
1438     argc        => 2,
1439     stream      => 1,
1440     record_type => 'bib'
1441 );
1442 __PACKAGE__->register_method(  
1443     api_name    => "open-ils.vandelay.queued_authority_record.html",
1444     method      => 'queued_record_html',
1445     api_level   => 1,
1446     argc        => 2,
1447     stream      => 1,
1448     record_type => 'auth'
1449 );
1450
1451 sub queued_record_html {
1452     my($self, $conn, $auth, $rec_id) = @_;
1453     my $e = new_editor(xact=>1,authtoken => $auth);
1454     return $e->die_event unless $e->checkauth;
1455     my $rec;
1456     if($self->{record_type} eq 'bib') {
1457         $rec = $e->retrieve_vandelay_queued_bib_record($rec_id)
1458             or return $e->die_event;
1459     } else {
1460         $rec = $e->retrieve_vandelay_queued_authority_record($rec_id)
1461             or return $e->die_event;
1462     }
1463
1464     $e->rollback;
1465     return $U->simplereq(
1466         'open-ils.search',
1467         'open-ils.search.biblio.record.html', undef, 1, $rec->marc);
1468 }
1469
1470
1471 __PACKAGE__->register_method(  
1472     api_name    => "open-ils.vandelay.bib_queue.summary.retrieve", 
1473     method      => 'retrieve_queue_summary',
1474     api_level   => 1,
1475     argc        => 2,
1476     stream      => 1,
1477     record_type => 'bib'
1478 );
1479 __PACKAGE__->register_method(  
1480     api_name    => "open-ils.vandelay.auth_queue.summary.retrieve",
1481     method      => 'retrieve_queue_summary',
1482     api_level   => 1,
1483     argc        => 2,
1484     stream      => 1,
1485     record_type => 'auth'
1486 );
1487
1488 sub retrieve_queue_summary {
1489     my($self, $conn, $auth, $queue_id) = @_;
1490     my $e = new_editor(xact=>1, authtoken => $auth);
1491     return $e->die_event unless $e->checkauth;
1492
1493     my $queue;
1494     my $type = $self->{record_type};
1495     if($type eq 'bib') {
1496         $queue = $e->retrieve_vandelay_bib_queue($queue_id)
1497             or return $e->die_event;
1498     } else {
1499         $queue = $e->retrieve_vandelay_authority_queue($queue_id)
1500             or return $e->die_event;
1501     }
1502
1503     my $evt = check_queue_perms($e, $type, $queue);
1504     return $evt if $evt;
1505
1506     my $search = 'search_vandelay_queued_bib_record';
1507     $search =~ s/bib/authority/ if $type ne 'bib';
1508
1509     my $summary = {
1510         queue => $queue,
1511         total => scalar(@{$e->$search({queue => $queue_id}, {idlist=>1})}),
1512         imported => scalar(@{$e->$search({queue => $queue_id, import_time => {'!=' => undef}}, {idlist=>1})}),
1513     };
1514
1515     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
1516     $summary->{rec_import_errors} = $e->json_query({
1517         select => {$class => [{alias => 'count', column => 'id', transform => 'count', aggregate => 1}]},
1518         from => $class,
1519         where => {queue => $queue_id, import_error => {'!=' => undef}}
1520     })->[0]->{count};
1521
1522     if($type eq 'bib') {
1523         
1524         # count of all items attached to records in the queue in question
1525         my $query = {
1526             select => {vii => [{alias => 'count', column => 'id', transform => 'count', aggregate => 1}]},
1527             from => 'vii',
1528             where => {
1529                 record => {
1530                     in => {
1531                         select => {vqbr => ['id']},
1532                         from => 'vqbr',
1533                         where => {queue => $queue_id}
1534                     }
1535                 }
1536             }
1537         };
1538         $summary->{total_items} = $e->json_query($query)->[0]->{count};
1539
1540         # count of items we attempted to import, but errored, attached to records in the queue in question
1541         $query->{where}->{import_error} = {'!=' => undef};
1542         $summary->{item_import_errors} = $e->json_query($query)->[0]->{count};
1543
1544         # count of items we successfully imported attached to records in the queue in question
1545         delete $query->{where}->{import_error};
1546         $query->{where}->{import_time} = {'!=' => undef};
1547         $summary->{total_items_imported} = $e->json_query($query)->[0]->{count};
1548     }
1549
1550     return $summary;
1551 }
1552
1553 # --------------------------------------------------------------------------------
1554 # Given a list of queued record IDs, imports all items attached to those records
1555 # --------------------------------------------------------------------------------
1556 sub import_record_asset_list_impl {
1557     my($conn, $rec_ids, $requestor) = @_;
1558
1559     my $roe = new_editor(xact=> 1, requestor => $requestor);
1560
1561     # for speed, filter out any records have not been 
1562     # imported or have no import items to load
1563     $rec_ids = $roe->json_query({
1564         select => {vqbr => ['id']},
1565         from => {vqbr => 'vii'},
1566         where => {'+vqbr' => {
1567             id => $rec_ids,
1568             import_time => {'!=' => undef}
1569         }},
1570         distinct => 1
1571     });
1572     $rec_ids = [map {$_->{id}} @$rec_ids];
1573
1574     my $report_args = {
1575         conn => $conn,
1576         total => scalar(@$rec_ids),
1577         step => 1, # how often to respond
1578         progress => 1,
1579         in_count => 0,
1580     };
1581
1582     for my $rec_id (@$rec_ids) {
1583         my $rec = $roe->retrieve_vandelay_queued_bib_record($rec_id);
1584         my $item_ids = $roe->search_vandelay_import_item(
1585             {record => $rec->id, import_error => undef}, 
1586             {idlist=>1}
1587         );
1588
1589         for my $item_id (@$item_ids) {
1590             my $e = new_editor(requestor => $requestor, xact => 1);
1591             my $item = $e->retrieve_vandelay_import_item($item_id);
1592             my ($copy, $vol, $evt);
1593
1594             $$report_args{import_item} = $item;
1595             $$report_args{e} = $e;
1596             $$report_args{import_error} = undef;
1597             $$report_args{evt} = undef;
1598
1599             if (my $copy_id = $item->internal_id) { # assignment
1600                 # copy matches an existing copy.  Overlay instead of create.
1601
1602                 $logger->info("vl: performing copy overlay for internal_id=$copy_id");
1603
1604                 my $qt = $e->json_query({
1605                     select => {vbq => ['queue_type']},
1606                     from => {vqbr => 'vbq'},
1607                     where => {'+vqbr' => {id => $rec_id}}
1608                 })->[0]->{queue_type};
1609
1610                 if ($qt eq 'acq') {
1611                     # internal_id for ACQ queues refers to acq.lineitem_detail.id
1612                     # pull the real copy id from the acq LID
1613
1614                     my $lid = $e->retrieve_acq_lineitem_detail($copy_id);
1615                     if (!$lid) {
1616                         $$report_args{evt} = $e->die_event;
1617                         respond_with_status($report_args);
1618                         next;
1619                     }
1620                     $copy_id = $lid->eg_copy_id;
1621                     $logger->info("vl: performing ACQ copy overlay for copy $copy_id");
1622                 }
1623
1624                 $copy = $e->search_asset_copy([
1625                     {id => $copy_id, deleted => 'f'},
1626                     {flesh => 1, flesh_fields => {acp => ['call_number']}}
1627                 ])->[0];
1628
1629                 if (!$copy) {
1630                     $$report_args{evt} = $e->die_event;
1631                     respond_with_status($report_args);
1632                     next;
1633                 }
1634
1635                 # prevent update of unrelated copies
1636                 if ($copy->call_number->record != $rec->imported_as) {
1637                     $logger->info("vl: attempt to overlay unrelated copy=$copy_id; rec=".$rec->imported_as);
1638
1639                     $evt = OpenILS::Event->new('INVALID_IMPORT_COPY_ID', 
1640                         note => 'Cannot overlay copies for unlinked bib',
1641                         bre => $rec->imported_as, 
1642                         copy_id => $copy_id
1643                     );
1644                     $$report_args{evt} = $evt;
1645                     respond_with_status($report_args);
1646                     next;
1647                 }
1648
1649                 # overlaying copies requires an extra permission
1650                 if (!$e->allowed("IMPORT_OVERLAY_COPY", $copy->call_number->owning_lib)) {
1651                     $$report_args{evt} = $e->die_event;
1652                     respond_with_status($report_args);
1653                     next;
1654                 }
1655
1656                 # are we updating the call-number?
1657                 if ($item->call_number and $item->call_number ne $copy->call_number->label) {
1658
1659                     my $count = $e->json_query({
1660                         select => {acp => [{
1661                             alias => 'count', 
1662                             column => 'id', 
1663                             transform => 'count', 
1664                             aggregate => 1
1665                         }]},
1666                         from => 'acp',
1667                         where => {
1668                             deleted => 'f',
1669                             call_number => $copy->call_number->id
1670                         }
1671                     })->[0]->{count};
1672
1673                     if ($count == 1) {
1674                         # if this is the only copy attached to this 
1675                         # callnumber, just update the callnumber
1676
1677                         $logger->info("vl: updating callnumber label in copy overlay");
1678
1679                         $copy->call_number->label($item->call_number);
1680                         if (!$e->update_asset_call_number($copy->call_number)) {
1681                             $$report_args{evt} = $e->die_event;
1682                             respond_with_status($report_args);
1683                             next;
1684                         }
1685
1686                     } else {
1687
1688                         # otherwise, move the copy to a new/existing 
1689                         # call-number with the given label/owner
1690                         # note that overlay does not allow the owning_lib 
1691                         # to be changed.  Should it?
1692
1693                         $logger->info("vl: moving copy to new callnumber in copy overlay");
1694
1695                         ($vol, $evt) =
1696                             OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1697                                 $e, $item->call_number, 
1698                                 $copy->call_number->record, 
1699                                 $copy->call_number->owning_lib
1700                             );
1701
1702                         if($evt) {
1703                             $$report_args{evt} = $evt;
1704                             respond_with_status($report_args);
1705                             next;
1706                         }
1707
1708                         $copy->call_number($vol);
1709                     }
1710                 } # cn-update
1711
1712                 # for every field that has a non-'' value, overlay the copy value
1713                 foreach (qw/ barcode location circ_lib status 
1714                     circulate deposit deposit_amount ref holdable 
1715                     price circ_as_type alert_message opac_visible circ_modifier/) {
1716
1717                     my $val = $item->$_();
1718                     $copy->$_($val) if $val and $val ne '';
1719                 }
1720
1721                 # de-flesh for update
1722                 $copy->call_number($copy->call_number->id);
1723                 $copy->ischanged(1);
1724
1725                 $evt = OpenILS::Application::Cat::AssetCommon->
1726                     update_fleshed_copies($e, {all => 1}, undef, [$copy]);
1727
1728                 if($evt) {
1729                     $$report_args{evt} = $evt;
1730                     respond_with_status($report_args);
1731                     next;
1732                 }
1733
1734             } else { 
1735
1736                 # Creating a new copy
1737                 $logger->info("vl: creating new copy in import");
1738
1739                 # --------------------------------------------------------------------------------
1740                 # Find or create the volume
1741                 # --------------------------------------------------------------------------------
1742                 my ($vol, $evt) =
1743                     OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1744                         $e, $item->call_number, $rec->imported_as, $item->owning_lib);
1745
1746                 if($evt) {
1747                     $$report_args{evt} = $evt;
1748                     respond_with_status($report_args);
1749                     next;
1750                 }
1751
1752                 # --------------------------------------------------------------------------------
1753                 # Create the new copy
1754                 # --------------------------------------------------------------------------------
1755                 $copy = Fieldmapper::asset::copy->new;
1756                 $copy->loan_duration(2);
1757                 $copy->fine_level(2);
1758                 $copy->barcode($item->barcode);
1759                 $copy->location($item->location);
1760                 $copy->circ_lib($item->circ_lib || $item->owning_lib);
1761                 $copy->status( defined($item->status) ? $item->status : OILS_COPY_STATUS_IN_PROCESS );
1762                 $copy->circulate($item->circulate);
1763                 $copy->deposit($item->deposit);
1764                 $copy->deposit_amount($item->deposit_amount);
1765                 $copy->ref($item->ref);
1766                 $copy->holdable($item->holdable);
1767                 $copy->price($item->price);
1768                 $copy->circ_as_type($item->circ_as_type);
1769                 $copy->alert_message($item->alert_message);
1770                 $copy->opac_visible($item->opac_visible);
1771                 $copy->circ_modifier($item->circ_modifier);
1772
1773                 # --------------------------------------------------------------------------------
1774                 # Check for dupe barcode
1775                 # --------------------------------------------------------------------------------
1776                 if($evt = OpenILS::Application::Cat::AssetCommon->create_copy($e, $vol, $copy)) {
1777                     $$report_args{evt} = $evt;
1778                     $$report_args{import_error} = 'import.item.duplicate.barcode'
1779                         if $evt->{textcode} eq 'ITEM_BARCODE_EXISTS';
1780                     respond_with_status($report_args);
1781                     next;
1782                 }
1783
1784                 # --------------------------------------------------------------------------------
1785                 # create copy notes
1786                 # --------------------------------------------------------------------------------
1787                 $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1788                     $e, $copy, '', $item->pub_note, 1) if $item->pub_note;
1789
1790                 if($evt) {
1791                     $$report_args{evt} = $evt;
1792                     respond_with_status($report_args);
1793                     next;
1794                 }
1795
1796                 $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1797                     $e, $copy, '', $item->priv_note) if $item->priv_note;
1798
1799                 if($evt) {
1800                     $$report_args{evt} = $evt;
1801                     respond_with_status($report_args);
1802                     next;
1803                 }
1804             }
1805
1806             # set the import data on the import item
1807             $item->imported_as($copy->id); # $copy->id is set by create_copy() ^--
1808             $item->import_time('now');
1809
1810             unless($e->update_vandelay_import_item($item)) {
1811                 $$report_args{evt} = $e->die_event;
1812                 respond_with_status($report_args);
1813                 next;
1814             }
1815
1816             # --------------------------------------------------------------------------------
1817             # Item import succeeded
1818             # --------------------------------------------------------------------------------
1819             $e->commit;
1820             $$report_args{in_count}++;
1821             respond_with_status($report_args);
1822             $logger->info("vl: successfully imported item " . $item->barcode);
1823         }
1824     }
1825
1826     $roe->rollback;
1827     return undef;
1828 }
1829
1830
1831 sub respond_with_status {
1832     my $args = shift;
1833     my $e = $$args{e};
1834
1835     #  If the import failed, track the failure reason
1836
1837     my $error = $$args{import_error};
1838     my $evt = $$args{evt};
1839
1840     if($error or $evt) {
1841
1842         my $item = $$args{import_item};
1843         $logger->info("vl: unable to import item " . $item->barcode);
1844
1845         $error ||= 'general.unknown';
1846         $item->import_error($error);
1847
1848         if($evt) {
1849             my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 140));
1850             $item->error_detail($detail);
1851         }
1852
1853         # state of the editor is unknown at this point.  Force a rollback and start over.
1854         $e->rollback;
1855         $e = new_editor(xact => 1);
1856         $e->update_vandelay_import_item($item);
1857         $e->commit;
1858     }
1859
1860     if($$args{report_all} or ($$args{progress} % $$args{step}) == 0) {
1861         $$args{conn}->respond({
1862             total => $$args{total},
1863             progress => $$args{progress},
1864             success_count => $$args{success_count},
1865             err_event => $evt
1866         });
1867         $$args{step} *= 2 unless $$args{step} == 256;
1868     }
1869
1870     $$args{progress}++;
1871 }
1872
1873 __PACKAGE__->register_method(  
1874     api_name    => "open-ils.vandelay.match_set.get_tree",
1875     method      => "match_set_get_tree",
1876     api_level   => 1,
1877     argc        => 2,
1878     signature   => {
1879         desc    => q/For a given vms object, return a tree of match set points
1880                     represented by a vmsp object with recursively fleshed
1881                     children./
1882     }
1883 );
1884
1885 sub match_set_get_tree {
1886     my ($self, $conn, $authtoken, $match_set_id) = @_;
1887
1888     $match_set_id = int($match_set_id) or return;
1889
1890     my $e = new_editor("authtoken" => $authtoken);
1891     $e->checkauth or return $e->die_event;
1892
1893     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1894         return $e->die_event;
1895
1896     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1897         return $e->die_event;
1898
1899     my $tree = $e->search_vandelay_match_set_point([
1900         {"match_set" => $match_set_id, "parent" => undef},
1901         {"flesh" => -1, "flesh_fields" => {"vmsp" => ["children"]}}
1902     ]) or return $e->die_event;
1903
1904     return pop @$tree;
1905 }
1906
1907
1908 __PACKAGE__->register_method(
1909     api_name    => "open-ils.vandelay.match_set.update",
1910     method      => "match_set_update_tree",
1911     api_level   => 1,
1912     argc        => 3,
1913     signature   => {
1914         desc => q/Replace any vmsp objects associated with a given (by ID) vms
1915                 with the given objects (recursively fleshed vmsp tree)./
1916     }
1917 );
1918
1919 sub _walk_new_vmsp {
1920     my ($e, $match_set_id, $node, $parent_id) = @_;
1921
1922     my $point = new Fieldmapper::vandelay::match_set_point;
1923     $point->parent($parent_id);
1924     $point->match_set($match_set_id);
1925     $point->$_($node->$_) for (qw/bool_op svf tag subfield negate quality/);
1926
1927     $e->create_vandelay_match_set_point($point) or return $e->die_event;
1928
1929     $parent_id = $e->data->id;
1930     if ($node->children && @{$node->children}) {
1931         for (@{$node->children}) {
1932             return $e->die_event if
1933                 _walk_new_vmsp($e, $match_set_id, $_, $parent_id);
1934         }
1935     }
1936
1937     return;
1938 }
1939
1940 sub match_set_update_tree {
1941     my ($self, $conn, $authtoken, $match_set_id, $tree) = @_;
1942
1943     my $e = new_editor("xact" => 1, "authtoken" => $authtoken);
1944     $e->checkauth or return $e->die_event;
1945
1946     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1947         return $e->die_event;
1948
1949     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1950         return $e->die_event;
1951
1952     my $existing = $e->search_vandelay_match_set_point([
1953         {"match_set" => $match_set_id},
1954         {"order_by" => {"vmsp" => "id DESC"}}
1955     ]) or return $e->die_event;
1956
1957     # delete points, working up from leaf points to the root
1958     while(@$existing) {
1959         for my $point (shift @$existing) {
1960             if( grep {$_->parent eq $point->id} @$existing) {
1961                 push(@$existing, $point);
1962             } else {
1963                 $e->delete_vandelay_match_set_point($point) or return $e->die_event;
1964             }
1965         }
1966     }
1967
1968     _walk_new_vmsp($e, $match_set_id, $tree);
1969
1970     $e->commit or return $e->die_event;
1971 }
1972
1973 __PACKAGE__->register_method(  
1974     api_name    => 'open-ils.vandelay.bib_queue.to_bucket',
1975     method      => 'bib_queue_to_bucket',
1976     api_level   => 1,
1977     argc        => 2,
1978     signature   => {
1979         desc    => q/Add to or create a new bib container (bucket) with the successfully 
1980                     imported contents of a vandelay queue.  Any user that has Vandelay 
1981                     queue create permissions can append or create buckets from his-her own queues./,
1982         params  => [
1983             {desc => 'Authtoken', type => 'string'},
1984             {desc => 'Queue ID', type => 'number'},
1985             {desc => 'Bucket Name', type => 'string'}
1986         ],
1987         return  => {desc => q/
1988             {bucket => $bucket, addcount => number-of-items-added-to-bucket, item_count => total-bucket-item-count} on success,
1989             {add_count => 0} if there is nothing to do, and Event on error/}
1990     }
1991 );
1992
1993 sub bib_queue_to_bucket {
1994     my ($self, $conn, $auth, $q_id, $bucket_name) = @_;
1995
1996     my $e = new_editor(xact => 1, authtoken => $auth);
1997     return $e->die_event unless $e->checkauth;
1998     
1999     my $queue = $e->retrieve_vandelay_bib_queue($q_id)
2000         or return $e->die_event;
2001
2002     return OpenILS::Event->new('BAD_PARAMS', 
2003         note => q/Bucket creator must be queue owner/)
2004         unless $queue->owner == $e->requestor->id;
2005
2006     # find the bib IDs that will go into the bucket
2007     my $bib_ids = $e->json_query({
2008         select => {vqbr => ['imported_as']},
2009         from => 'vqbr',
2010         where => {queue => $q_id, imported_as => {'!=' => undef}}
2011     });
2012
2013     if (!@$bib_ids) { # no records to add
2014         $e->rollback;
2015         return {add_count => 0};
2016     }
2017
2018     # allow user to add to an existing bucket by name
2019     my $bucket = $e->search_container_biblio_record_entry_bucket({
2020         owner => $e->requestor->id, 
2021         name => $bucket_name,
2022         btype => 'vandelay_queue'
2023     })->[0];
2024
2025     # if the bucket does not exist, create a new one
2026     if (!$bucket) { 
2027         $bucket = Fieldmapper::container::biblio_record_entry_bucket->new;
2028         $bucket->name($bucket_name);
2029         $bucket->owner($e->requestor->id);
2030         $bucket->btype('vandelay_queue');
2031
2032         $e->create_container_biblio_record_entry_bucket($bucket)
2033             or return $e->die_event;
2034     }
2035
2036     # create the new bucket items
2037     for my $bib_id ( map {$_->{imported_as}} @$bib_ids ) {
2038         my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
2039         $item->target_biblio_record_entry($bib_id);
2040         $item->bucket($bucket->id);
2041         $e->create_container_biblio_record_entry_bucket_item($item)
2042             or return $e->die_event;
2043     }
2044
2045     # re-fetch the bucket to pick up the correct create_time
2046     $bucket = $e->retrieve_container_biblio_record_entry_bucket($bucket->id)
2047         or return $e->die_event;
2048
2049     # get the total count of items in this bucket
2050     my $count = $e->json_query({
2051         select => {cbrebi => [{
2052             aggregate =>  1,
2053             transform => 'count',
2054             alias => 'count',
2055             column => 'id'
2056         }]},
2057         from => 'cbrebi',
2058         where => {bucket => $bucket->id}
2059     })->[0];
2060
2061     $e->commit;
2062
2063     return {
2064         bucket => $bucket, 
2065         add_count => scalar(@$bib_ids), # items added to the bucket
2066         item_count => $count->{count} # total items in buckets
2067     };
2068 }
2069
2070 1;