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