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