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