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