]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Vandelay.pm
Merge branch 'master' of git.evergreen-ils.org:Evergreen into template-toolkit-opac...
[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 MARC::Batch;
13 use MARC::Record;
14 use MARC::File::XML ( BinaryEncoding => 'UTF-8' );
15 use OpenILS::Utils::Fieldmapper;
16 use Time::HiRes qw(time);
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use MIME::Base64;
19 use OpenILS::Const qw/:const/;
20 use OpenILS::Application::AppUtils;
21 use OpenILS::Application::Cat::BibCommon;
22 use OpenILS::Application::Cat::AuthCommon;
23 use OpenILS::Application::Cat::AssetCommon;
24 my $U = 'OpenILS::Application::AppUtils';
25
26 # A list of LDR/06 values from http://loc.gov/marc
27 my %record_types = (
28         a => 'bib',
29         c => 'bib',
30         d => 'bib',
31         e => 'bib',
32         f => 'bib',
33         g => 'bib',
34         i => 'bib',
35         j => 'bib',
36         k => 'bib',
37         m => 'bib',
38         o => 'bib',
39         p => 'bib',
40         r => 'bib',
41         t => 'bib',
42         u => 'holdings',
43         v => 'holdings',
44         x => 'holdings',
45         y => 'holdings',
46         z => 'auth',
47       ' ' => 'bib',
48 );
49
50 sub initialize {}
51 sub child_init {}
52
53 # --------------------------------------------------------------------------------
54 # Biblio ingest
55
56 sub create_bib_queue {
57     my $self = shift;
58     my $client = shift;
59     my $auth = shift;
60     my $name = shift;
61     my $owner = shift;
62     my $type = shift;
63     my $match_set = shift;
64     my $import_def = shift;
65
66     my $e = new_editor(authtoken => $auth, xact => 1);
67
68     return $e->die_event unless $e->checkauth;
69     return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
70     $owner ||= $e->requestor->id;
71
72     if ($e->search_vandelay_bib_queue( {name => $name, owner => $owner, queue_type => $type})->[0]) {
73         $e->rollback;
74         return OpenILS::Event->new('BIB_QUEUE_EXISTS') 
75     }
76
77     my $queue = new Fieldmapper::vandelay::bib_queue();
78     $queue->name( $name );
79     $queue->owner( $owner );
80     $queue->queue_type( $type ) if ($type);
81     $queue->item_attr_def( $import_def ) if ($import_def);
82     $queue->match_set($match_set) if $match_set;
83
84     my $new_q = $e->create_vandelay_bib_queue( $queue );
85     return $e->die_event unless ($new_q);
86     $e->commit;
87
88     return $new_q;
89 }
90 __PACKAGE__->register_method(  
91     api_name   => "open-ils.vandelay.bib_queue.create",
92     method     => "create_bib_queue",
93     api_level  => 1,
94     argc       => 4,
95 );                      
96
97
98 sub create_auth_queue {
99     my $self = shift;
100     my $client = shift;
101     my $auth = shift;
102     my $name = shift;
103     my $owner = shift;
104     my $type = shift;
105     my $match_set = shift;
106
107     my $e = new_editor(authtoken => $auth, xact => 1);
108
109     return $e->die_event unless $e->checkauth;
110     return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
111     $owner ||= $e->requestor->id;
112
113     if ($e->search_vandelay_bib_queue({name => $name, owner => $owner, queue_type => $type})->[0]) {
114         $e->rollback;
115         return OpenILS::Event->new('AUTH_QUEUE_EXISTS') 
116     }
117
118     my $queue = new Fieldmapper::vandelay::authority_queue();
119     $queue->name( $name );
120     $queue->owner( $owner );
121     $queue->queue_type( $type ) if ($type);
122
123     my $new_q = $e->create_vandelay_authority_queue( $queue );
124     $e->die_event unless ($new_q);
125     $e->commit;
126
127     return $new_q;
128 }
129 __PACKAGE__->register_method(  
130     api_name   => "open-ils.vandelay.authority_queue.create",
131     method     => "create_auth_queue",
132     api_level  => 1,
133     argc       => 3,
134 );                      
135
136 sub add_record_to_bib_queue {
137     my $self = shift;
138     my $client = shift;
139     my $auth = shift;
140     my $queue = shift;
141     my $marc = shift;
142     my $purpose = shift;
143     my $bib_source = shift;
144
145     my $e = new_editor(authtoken => $auth, xact => 1);
146
147     $queue = $e->retrieve_vandelay_bib_queue($queue);
148
149     return $e->die_event unless $e->checkauth;
150     return $e->die_event unless
151         ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
152          $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
153
154     my $new_rec = _add_bib_rec($e, $marc, $queue->id, $purpose, $bib_source);
155
156     return $e->die_event unless ($new_rec);
157     $e->commit;
158     return $new_rec;
159 }
160 __PACKAGE__->register_method(  
161     api_name   => "open-ils.vandelay.queued_bib_record.create",
162     method     => "add_record_to_bib_queue",
163     api_level  => 1,
164     argc       => 3,
165 );                      
166
167 sub _add_bib_rec {
168     my $e = shift;
169     my $marc = shift;
170     my $queue = shift;
171     my $purpose = shift;
172     my $bib_source = shift;
173
174     my $rec = new Fieldmapper::vandelay::queued_bib_record();
175     $rec->marc( $marc );
176     $rec->queue( $queue );
177     $rec->purpose( $purpose ) if ($purpose);
178     $rec->bib_source($bib_source);
179
180     return $e->create_vandelay_queued_bib_record( $rec );
181 }
182
183 sub add_record_to_authority_queue {
184     my $self = shift;
185     my $client = shift;
186     my $auth = shift;
187     my $queue = shift;
188     my $marc = shift;
189     my $purpose = shift;
190
191     my $e = new_editor(authtoken => $auth, xact => 1);
192
193     $queue = $e->retrieve_vandelay_authority_queue($queue);
194
195     return $e->die_event unless $e->checkauth;
196     return $e->die_event unless
197         ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
198          $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
199
200     my $new_rec = _add_auth_rec($e, $marc, $queue->id, $purpose);
201
202     return $e->die_event unless ($new_rec);
203     $e->commit;
204     return $new_rec;
205 }
206 __PACKAGE__->register_method(
207     api_name   => "open-ils.vandelay.queued_authority_record.create",
208     method     => "add_record_to_authority_queue",
209     api_level  => 1,
210     argc       => 3,
211 );
212
213 sub _add_auth_rec {
214     my $e = shift;
215     my $marc = shift;
216     my $queue = shift;
217     my $purpose = shift;
218
219     my $rec = new Fieldmapper::vandelay::queued_authority_record();
220     $rec->marc( $marc );
221     $rec->queue( $queue );
222     $rec->purpose( $purpose ) if ($purpose);
223
224     return $e->create_vandelay_queued_authority_record( $rec );
225 }
226
227 sub process_spool {
228     my $self = shift;
229     my $client = shift;
230     my $auth = shift;
231     my $fingerprint = shift || '';
232     my $queue_id = shift;
233     my $purpose = shift;
234     my $filename = shift;
235     my $bib_source = shift;
236
237     my $e = new_editor(authtoken => $auth, xact => 1);
238     return $e->die_event unless $e->checkauth;
239
240     my $queue;
241     my $type = $self->{record_type};
242
243     if($type eq 'bib') {
244         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
245     } else {
246         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
247     }
248
249     my $evt = check_queue_perms($e, $type, $queue);
250     return $evt if ($evt);
251
252     my $cache = new OpenSRF::Utils::Cache();
253
254     if($fingerprint) {
255         my $data = $cache->get_cache('vandelay_import_spool_' . $fingerprint);
256         $purpose = $data->{purpose};
257         $filename = $data->{path};
258         $bib_source = $data->{bib_source};
259     }
260
261     unless(-r $filename) {
262         $logger->error("unable to read MARC file $filename");
263         return -1; # make this an event XXX
264     }
265
266     $logger->info("vandelay spooling $fingerprint purpose=$purpose file=$filename");
267
268     my $marctype = 'USMARC'; 
269
270     open F, $filename;
271     $marctype = 'XML' if (getc(F) =~ /^\D/o);
272     close F;
273
274     my $batch = new MARC::Batch ($marctype, $filename);
275     $batch->strict_off;
276
277     my $response_scale = 10;
278     my $count = 0;
279     my $r = -1;
280     while (try { $r = $batch->next } otherwise { $r = -1 }) {
281         if ($r == -1) {
282             $logger->warn("Processing of record $count in set $filename failed.  Skipping this record");
283             $count++;
284         }
285
286         $logger->info("processing record $count");
287
288         try {
289             (my $xml = $r->as_xml_record()) =~ s/\n//sog;
290             $xml =~ s/^<\?xml.+\?\s*>//go;
291             $xml =~ s/>\s+</></go;
292             $xml =~ s/\p{Cc}//go;
293             $xml = $U->entityize($xml);
294             $xml =~ s/[\x00-\x1f]//go;
295
296             my $qrec;
297             # Check the leader to ensure we've got something resembling the expected
298             # Allow spaces to give records the benefit of the doubt
299             my $ldr_type = substr($r->leader(), 6, 1);
300             if ($type eq 'bib' && ($record_types{$ldr_type}) eq 'bib' || $ldr_type eq ' ') {
301                 $qrec = _add_bib_rec( $e, $xml, $queue_id, $purpose, $bib_source ) or return $e->die_event;
302             } elsif ($type eq 'auth' && ($record_types{$ldr_type}) eq 'auth' || $ldr_type eq ' ') {
303                 $qrec = _add_auth_rec( $e, $xml, $queue_id, $purpose ) or return $e->die_event;
304             } else {
305                 # I don't know how to handle this type; rock on
306                 $logger->error("In process_spool(), type was $type and leader type was $ldr_type ; not currently supported");
307                 next;
308             }
309
310             if($self->api_name =~ /stream_results/ and $qrec) {
311                 $client->respond($qrec->id)
312             } else {
313                 $client->respond($count) if (++$count % $response_scale) == 0;
314                 $response_scale *= 10 if ($count == ($response_scale * 10));
315             }
316         } catch Error with {
317             my $error = shift;
318             $logger->warn("Encountered a bad record at Vandelay ingest: ".$error);
319         }
320     }
321
322     $e->commit;
323     unlink($filename);
324     $cache->delete_cache('vandelay_import_spool_' . $fingerprint) if $fingerprint;
325     return $count;
326 }
327
328 __PACKAGE__->register_method(  
329     api_name    => "open-ils.vandelay.bib.process_spool",
330     method      => "process_spool",
331     api_level   => 1,
332     argc        => 3,
333     max_chunk_size => 0,
334     record_type => 'bib'
335 );                      
336 __PACKAGE__->register_method(  
337     api_name    => "open-ils.vandelay.auth.process_spool",
338     method      => "process_spool",
339     api_level   => 1,
340     argc        => 3,
341     max_chunk_size => 0,
342     record_type => 'auth'
343 );                      
344
345 __PACKAGE__->register_method(  
346     api_name    => "open-ils.vandelay.bib.process_spool.stream_results",
347     method      => "process_spool",
348     api_level   => 1,
349     argc        => 3,
350     stream      => 1,
351     max_chunk_size => 0,
352     record_type => 'bib'
353 );                      
354 __PACKAGE__->register_method(  
355     api_name    => "open-ils.vandelay.auth.process_spool.stream_results",
356     method      => "process_spool",
357     api_level   => 1,
358     argc        => 3,
359     stream      => 1,
360     max_chunk_size => 0,
361     record_type => 'auth'
362 );
363
364 __PACKAGE__->register_method(  
365     api_name    => "open-ils.vandelay.bib_queue.records.retrieve",
366     method      => 'retrieve_queued_records',
367     api_level   => 1,
368     argc        => 2,
369     stream      => 1,
370     record_type => 'bib'
371 );
372 __PACKAGE__->register_method(
373     api_name    => "open-ils.vandelay.bib_queue.records.retrieve.export.print",
374     method      => 'retrieve_queued_records',
375     api_level   => 1,
376     argc        => 2,
377     stream      => 1,
378     record_type => 'bib'
379 );
380 __PACKAGE__->register_method(
381     api_name    => "open-ils.vandelay.bib_queue.records.retrieve.export.csv",
382     method      => 'retrieve_queued_records',
383     api_level   => 1,
384     argc        => 2,
385     stream      => 1,
386     record_type => 'bib'
387 );
388 __PACKAGE__->register_method(
389     api_name    => "open-ils.vandelay.bib_queue.records.retrieve.export.email",
390     method      => 'retrieve_queued_records',
391     api_level   => 1,
392     argc        => 2,
393     stream      => 1,
394     record_type => 'bib'
395 );
396
397 __PACKAGE__->register_method(  
398     api_name    => "open-ils.vandelay.auth_queue.records.retrieve",
399     method      => 'retrieve_queued_records',
400     api_level   => 1,
401     argc        => 2,
402     stream      => 1,
403     record_type => 'auth'
404 );
405 __PACKAGE__->register_method(
406     api_name    => "open-ils.vandelay.auth_queue.records.retrieve.export.print",
407     method      => 'retrieve_queued_records',
408     api_level   => 1,
409     argc        => 2,
410     stream      => 1,
411     record_type => 'auth'
412 );
413 __PACKAGE__->register_method(
414     api_name    => "open-ils.vandelay.auth_queue.records.retrieve.export.csv",
415     method      => 'retrieve_queued_records',
416     api_level   => 1,
417     argc        => 2,
418     stream      => 1,
419     record_type => 'auth'
420 );
421 __PACKAGE__->register_method(
422     api_name    => "open-ils.vandelay.auth_queue.records.retrieve.export.email",
423     method      => 'retrieve_queued_records',
424     api_level   => 1,
425     argc        => 2,
426     stream      => 1,
427     record_type => 'auth'
428 );
429
430 __PACKAGE__->register_method(  
431     api_name    => "open-ils.vandelay.bib_queue.records.matches.retrieve",
432     method      => 'retrieve_queued_records',
433     api_level   => 1,
434     argc        => 2,
435     stream      => 1,
436     record_type => 'bib',
437     signature   => {
438         desc => q/Only retrieve queued bib records that have matches against existing records/
439     }
440 );
441 __PACKAGE__->register_method(  
442     api_name    => "open-ils.vandelay.auth_queue.records.matches.retrieve",
443     method      => 'retrieve_queued_records',
444     api_level   => 1,
445     argc        => 2,
446     stream      => 1,
447     record_type => 'auth',
448     signature   => {
449         desc => q/Only retrieve queued authority records that have matches against existing records/
450     }
451 );
452
453 sub retrieve_queued_records {
454     my($self, $conn, $auth, $queue_id, $options) = @_;
455
456     $options ||= {};
457     my $limit = $$options{limit} || 20;
458     my $offset = $$options{offset} || 0;
459     my $type = $self->{record_type};
460
461     my $e = new_editor(authtoken => $auth, xact => 1);
462     return $e->die_event unless $e->checkauth;
463
464     my $queue;
465     if($type eq 'bib') {
466         $queue = $e->retrieve_vandelay_bib_queue($queue_id) or return $e->die_event;
467     } else {
468         $queue = $e->retrieve_vandelay_authority_queue($queue_id) or return $e->die_event;
469     }
470     my $evt = check_queue_perms($e, $type, $queue);
471     return $evt if ($evt);
472
473     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
474     my $query = {
475         select => {$class => ['id']},
476         from => $class,
477         where => {queue => $queue_id},
478         distinct => 1,
479         order_by => {$class => ['id']}, 
480         limit => $limit,
481         offset => $offset,
482     };
483     if($self->api_name =~ /export/) {
484         delete $query->{limit};
485         delete $query->{offset};
486     }
487
488     $query->{where}->{import_time} = undef if $$options{non_imported};
489
490     if($$options{with_import_error}) {
491
492         $query->{from} = {$class => {vii => {type => 'left'}}};
493         $query->{where}->{'-or'} = [
494             {'+vqbr' => {import_error => {'!=' => undef}}},
495             {'+vii' => {import_error => {'!=' => undef}}}
496         ];
497
498     } else {
499         
500         if($$options{with_rec_import_error}) {
501             $query->{where}->{import_error} = {'!=' => undef};
502
503         } elsif( $$options{with_item_import_error} and $type eq 'bib') {
504
505             $query->{from} = {$class => 'vii'};
506             $query->{where}->{'+vii'} = {import_error => {'!=' => undef}};
507         }
508     }
509
510     if($self->api_name =~ /matches/) {
511         # find only records that have matches
512         my $mclass = $type eq 'bib' ? 'vbm' : 'vam';
513         $query->{from} = {$class => {$mclass => {type => 'right'}}};
514     } 
515
516     my $record_ids = $e->json_query($query);
517
518     my $retrieve = ($type eq 'bib') ? 
519         'retrieve_vandelay_queued_bib_record' : 'retrieve_vandelay_queued_authority_record';
520     my $search = ($type eq 'bib') ? 
521         'search_vandelay_queued_bib_record' : 'search_vandelay_queued_authority_record';
522
523     if ($self->api_name =~ /export/) {
524         my $rec_list = $e->$search({id => [map { $_->{id} } @$record_ids]});
525         if ($self->api_name =~ /print/) {
526
527             $e->rollback;
528             return $U->fire_object_event(
529                 undef,
530                 'vandelay.queued_'.$type.'_record.print',
531                 $rec_list,
532                 $e->requestor->ws_ou
533             );
534
535         } elsif ($self->api_name =~ /csv/) {
536
537             $e->rollback;
538             return $U->fire_object_event(
539                 undef,
540                 'vandelay.queued_'.$type.'_record.csv',
541                 $rec_list,
542                 $e->requestor->ws_ou
543             );
544
545         } elsif ($self->api_name =~ /email/) {
546
547             $conn->respond_complete(1);
548
549             for my $rec (@$rec_list) {
550                 $U->create_events_for_hook(
551                     'vandelay.queued_'.$type.'_record.email',
552                     $rec,
553                     $e->requestor->home_ou,
554                     undef,
555                     undef,
556                     1
557                 );
558             }
559
560         }
561     } else {
562         for my $rec_id (@$record_ids) {
563             my $flesh = ['attributes', 'matches'];
564             push(@$flesh, 'import_items') if $$options{flesh_import_items};
565             my $params = {flesh => 1, flesh_fields => {$class => $flesh}};
566             my $rec = $e->$retrieve([$rec_id->{id}, $params]);
567             $rec->clear_marc if $$options{clear_marc};
568             $conn->respond($rec);
569         }
570     }
571
572     $e->rollback;
573     return undef;
574 }
575
576 __PACKAGE__->register_method(  
577     api_name    => 'open-ils.vandelay.import_item.queue.retrieve',
578     method      => 'retrieve_queue_import_items',
579     api_level   => 1,
580     argc        => 2,
581     stream      => 1,
582     authoritative => 1,
583     signature => q/
584         Returns Import Item (vii) objects for the selected queue.
585         Filter options:
586             with_import_error : only return items that failed to import
587     /
588 );
589 __PACKAGE__->register_method(
590     api_name    => 'open-ils.vandelay.import_item.queue.export.print',
591     method      => 'retrieve_queue_import_items',
592     api_level   => 1,
593     argc        => 2,
594     stream      => 1,
595     authoritative => 1,
596     signature => q/
597         Returns template-generated printable output of Import Item (vii) objects for the selected queue.
598         Filter options:
599             with_import_error : only return items that failed to import
600     /
601 );
602 __PACKAGE__->register_method(
603     api_name    => 'open-ils.vandelay.import_item.queue.export.csv',
604     method      => 'retrieve_queue_import_items',
605     api_level   => 1,
606     argc        => 2,
607     stream      => 1,
608     authoritative => 1,
609     signature => q/
610         Returns template-generated CSV output of Import Item (vii) objects for the selected queue.
611         Filter options:
612             with_import_error : only return items that failed to import
613     /
614 );
615 __PACKAGE__->register_method(
616     api_name    => 'open-ils.vandelay.import_item.queue.export.email',
617     method      => 'retrieve_queue_import_items',
618     api_level   => 1,
619     argc        => 2,
620     stream      => 1,
621     authoritative => 1,
622     signature => q/
623         Emails template-generated output of Import Item (vii) objects for the selected queue.
624         Filter options:
625             with_import_error : only return items that failed to import
626     /
627 );
628
629 sub retrieve_queue_import_items {
630     my($self, $conn, $auth, $q_id, $options) = @_;
631
632     $options ||= {};
633     my $limit = $$options{limit} || 20;
634     my $offset = $$options{offset} || 0;
635
636     my $e = new_editor(authtoken => $auth);
637     return $e->event unless $e->checkauth;
638
639     my $queue = $e->retrieve_vandelay_bib_queue($q_id) or return $e->event;
640     my $evt = check_queue_perms($e, 'bib', $queue);
641     return $evt if $evt;
642
643     my $query = {
644         select => {vii => ['id']},
645         from => {
646             vii => {
647                 vqbr => {
648                     join => {
649                         'vbq' => {
650                             field => 'id',
651                             fkey => 'queue',
652                             filter => {id => $q_id}
653                         }
654                     }
655                 }
656             }
657         },
658         order_by => {'vii' => ['record','id']},
659         limit => $limit,
660         offset => $offset
661     };
662     if($self->api_name =~ /export/) {
663         delete $query->{limit};
664         delete $query->{offset};
665     }
666
667     $query->{where} = {'+vii' => {import_error => {'!=' => undef}}}
668         if $$options{with_import_error};
669
670     my $items = $e->json_query($query);
671     my $item_list = $e->search_vandelay_import_item({id => [map { $_->{id} } @$items]});
672     if ($self->api_name =~ /export/) {
673         if ($self->api_name =~ /print/) {
674
675             return $U->fire_object_event(
676                 undef,
677                 'vandelay.import_items.print',
678                 $item_list,
679                 $e->requestor->ws_ou
680             );
681
682         } elsif ($self->api_name =~ /csv/) {
683
684             return $U->fire_object_event(
685                 undef,
686                 'vandelay.import_items.csv',
687                 $item_list,
688                 $e->requestor->ws_ou
689             );
690
691         } elsif ($self->api_name =~ /email/) {
692
693             $conn->respond_complete(1);
694
695             for my $item (@$item_list) {
696                 $U->create_events_for_hook(
697                     'vandelay.import_items.email',
698                     $item,
699                     $e->requestor->home_ou,
700                     undef,
701                     undef,
702                     1
703                 );
704             }
705
706         }
707     } else {
708         for my $item (@$item_list) {
709             $conn->respond($item);
710         }
711     }
712
713     return undef;
714 }
715
716 sub check_queue_perms {
717     my($e, $type, $queue) = @_;
718     if ($type eq 'bib') {
719         return $e->die_event unless
720             ($e->allowed('CREATE_BIB_IMPORT_QUEUE', undef, $queue) ||
721              $e->allowed('CREATE_BIB_IMPORT_QUEUE'));
722     } else {
723         return $e->die_event unless
724             ($e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE', undef, $queue) ||
725              $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE'));
726     }
727
728     return undef;
729 }
730
731 __PACKAGE__->register_method(  
732     api_name    => "open-ils.vandelay.bib_record.list.import",
733     method      => 'import_record_list',
734     api_level   => 1,
735     argc        => 2,
736     stream      => 1,
737     record_type => 'bib'
738 );
739
740 __PACKAGE__->register_method(  
741     api_name    => "open-ils.vandelay.auth_record.list.import",
742     method      => 'import_record_list',
743     api_level   => 1,
744     argc        => 2,
745     stream      => 1,
746     record_type => 'auth'
747 );
748
749 sub import_record_list {
750     my($self, $conn, $auth, $rec_ids, $args) = @_;
751     my $e = new_editor(authtoken => $auth, xact => 1);
752     return $e->die_event unless $e->checkauth;
753     $args ||= {};
754     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $args);
755     try {$e->rollback} otherwise {}; 
756     return $err if $err;
757     return {complete => 1};
758 }
759
760
761 __PACKAGE__->register_method(  
762     api_name    => "open-ils.vandelay.bib_queue.import",
763     method      => 'import_queue',
764     api_level   => 1,
765     argc        => 2,
766     stream      => 1,
767     max_chunk_size => 0,
768     record_type => 'bib',
769     signature => {
770         desc => q/
771             Attempts to import all non-imported records for the selected queue.
772             Will also attempt import of all non-imported items.
773         /
774     }
775 );
776
777 __PACKAGE__->register_method(  
778     api_name    => "open-ils.vandelay.auth_queue.import",
779     method      => 'import_queue',
780     api_level   => 1,
781     argc        => 2,
782     stream      => 1,
783     max_chunk_size => 0,
784     record_type => 'auth'
785 );
786
787 sub import_queue {
788     my($self, $conn, $auth, $q_id, $options) = @_;
789     my $e = new_editor(authtoken => $auth, xact => 1);
790     return $e->die_event unless $e->checkauth;
791     $options ||= {};
792     my $type = $self->{record_type};
793     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
794
795     # First, collect the not-yet-imported records
796     my $query = {queue => $q_id, import_time => undef};
797     my $search = ($type eq 'bib') ? 
798         'search_vandelay_queued_bib_record' : 
799         'search_vandelay_queued_authority_record';
800     my $rec_ids = $e->$search($query, {idlist => 1});
801
802     # Now add any imported records that have un-imported items
803
804     if($type eq 'bib') {
805         my $item_recs = $e->json_query({
806             select => {vqbr => ['id']},
807             from => {vqbr => 'vii'},
808             where => {
809                 '+vqbr' => {
810                     queue => $q_id,
811                     import_time => {'!=' => undef}
812                 },
813                 '+vii' => {import_time => undef}
814             },
815             distinct => 1
816         });
817         push(@$rec_ids, map {$_->{id}} @$item_recs);
818     }
819
820     my $err = import_record_list_impl($self, $conn, $rec_ids, $e->requestor, $options);
821     try {$e->rollback} otherwise {}; # only using this to make the read authoritative -- don't die from it
822     return $err if $err;
823     return {complete => 1};
824 }
825
826 # returns a list of queued record IDs for a given queue that 
827 # have at least one entry in the match table
828 # XXX DEPRECATED?
829 sub queued_records_with_matches {
830     my($e, $type, $q_id, $limit, $offset, $filter) = @_;
831
832     my $match_class = 'vbm';
833     my $rec_class = 'vqbr';
834     if($type eq 'auth') {
835         $match_class = 'vam';
836          $rec_class = 'vqar';
837     }
838
839     $filter ||= {};
840     $filter->{queue} = $q_id;
841
842     my $query = {
843         distinct => 1, 
844         select => {$match_class => ['queued_record']}, 
845         from => {
846             $match_class => {
847                 $rec_class => {
848                     field => 'id',
849                     fkey => 'queued_record',
850                     filter => $filter,
851                 }
852             }
853         }
854     };        
855
856     if($limit or defined $offset) {
857         $limit ||= 20;
858         $offset ||= 0;
859         $query->{limit} = $limit;
860         $query->{offset} = $offset;
861     }
862
863     my $data = $e->json_query($query);
864     return [ map {$_->{queued_record}} @$data ];
865 }
866
867
868 sub import_record_list_impl {
869     my($self, $conn, $rec_ids, $requestor, $args) = @_;
870
871     my $overlay_map = $args->{overlay_map} || {};
872     my $type = $self->{record_type};
873     my %queues;
874
875     my $report_args = {
876         progress => 1,
877         step => 1,
878         conn => $conn,
879         total => scalar(@$rec_ids),
880         report_all => $$args{report_all}
881     };
882
883     my $auto_overlay_exact = $$args{auto_overlay_exact};
884     my $auto_overlay_1match = $$args{auto_overlay_1match};
885     my $auto_overlay_best = $$args{auto_overlay_best_match};
886     my $match_quality_ratio = $$args{match_quality_ratio};
887     my $merge_profile = $$args{merge_profile};
888     my $bib_source = $$args{bib_source};
889     my $import_no_match = $$args{import_no_match};
890
891     my $overlay_func = 'vandelay.overlay_bib_record';
892     my $auto_overlay_func = 'vandelay.auto_overlay_bib_record';
893     my $auto_overlay_best_func = 'vandelay.auto_overlay_bib_record_with_best'; # XXX bib-only
894     my $retrieve_func = 'retrieve_vandelay_queued_bib_record';
895     my $update_func = 'update_vandelay_queued_bib_record';
896     my $search_func = 'search_vandelay_queued_bib_record';
897     my $retrieve_queue_func = 'retrieve_vandelay_bib_queue';
898     my $update_queue_func = 'update_vandelay_bib_queue';
899     my $rec_class = 'vqbr';
900
901     my $editor = new_editor();
902
903     my %bib_sources;
904     my $sources = $editor->search_config_bib_source({id => {'!=' => undef}});
905     $bib_sources{$_->id} = $_->source for @$sources;
906
907     if($type eq 'auth') {
908         $overlay_func =~ s/bib/auth/o;
909         $auto_overlay_func = s/bib/auth/o;
910         $retrieve_func =~ s/bib/authority/o;
911         $retrieve_queue_func =~ s/bib/authority/o;
912         $update_queue_func =~ s/bib/authority/o;
913         $update_func =~ s/bib/authority/o;
914         $search_func =~ s/bib/authority/o;
915         $rec_class = 'vqar';
916     }
917
918     my @success_rec_ids;
919     for my $rec_id (@$rec_ids) {
920
921         my $error = 0;
922         my $overlay_target = $overlay_map->{$rec_id};
923
924         my $e = new_editor(xact => 1);
925         $e->requestor($requestor);
926
927         $$report_args{e} = $e;
928         $$report_args{evt} = undef;
929         $$report_args{import_error} = undef;
930
931         my $rec = $e->$retrieve_func([
932             $rec_id,
933             {   flesh => 1,
934                 flesh_fields => { $rec_class => ['matches']},
935             }
936         ]);
937
938         unless($rec) {
939             $$report_args{evt} = $e->event;
940             finish_rec_import_attempt($report_args);
941             next;
942         }
943
944         if($rec->import_time) {
945             # if the record is already imported, that means it may have 
946             # un-imported copies.  Add to success list for later processing.
947             push(@success_rec_ids, $rec_id);
948             $e->rollback;
949             next;
950         }
951
952         $$report_args{rec} = $rec;
953         $queues{$rec->queue} = 1;
954
955         my $record;
956         my $imported = 0;
957
958         if(defined $overlay_target) {
959             # Caller chose an explicit overlay target
960
961             my $res = $e->json_query(
962                 {
963                     from => [
964                         $overlay_func,
965                         $rec_id,
966                         $overlay_target, 
967                         $merge_profile
968                     ]
969                 }
970             );
971
972             if($res and ($res = $res->[0])) {
973
974                 if($res->{$overlay_func} eq 't') {
975                     $logger->info("vl: $type direct overlay succeeded for queued rec ".
976                         "$rec_id and overlay target $overlay_target");
977                     $imported = 1;
978                 }
979
980             } else {
981                 $error = 1;
982                 $logger->error("vl: Error attempting overlay with func=$overlay_func, profile=$merge_profile, record=$rec_id");
983             }
984
985         } else {
986
987             if($auto_overlay_1match) { # overlay if there is exactly 1 match
988
989                 my %match_recs = map { $_->eg_record => 1 } @{$rec->matches};
990
991                 if( scalar(keys %match_recs) == 1) { # all matches point to the same record
992
993                     # $auto_overlay_best_func will find the 1 match and 
994                     # overlay if the quality ratio allows it
995
996                     my $res = $e->json_query(
997                         {
998                             from => [
999                                 $auto_overlay_best_func,
1000                                 $rec_id, 
1001                                 $merge_profile,
1002                                 $match_quality_ratio
1003                             ]
1004                         }
1005                     );
1006
1007                     if($res and ($res = $res->[0])) {
1008     
1009                         if($res->{$auto_overlay_best_func} eq 't') {
1010                             $logger->info("vl: $type overlay-1match succeeded for queued rec $rec_id");
1011                             $imported = 1;
1012
1013                             # re-fetch the record to pick up the imported_as value from the DB
1014                             $$report_args{rec} = $rec = $e->$retrieve_func([
1015                                 $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1016
1017
1018                         } else {
1019                             $$report_args{import_error} = 'overlay.record.quality' if $match_quality_ratio > 0;
1020                             $logger->info("vl: $type overlay-1match failed for queued rec $rec_id");
1021                         }
1022
1023                     } else {
1024                         $error = 1;
1025                         $logger->error("vl: Error attempting overlay with func=$auto_overlay_best_func, profile=$merge_profile, record=$rec_id");
1026                     }
1027                 }
1028             }
1029
1030             if(!$imported and !$error and $auto_overlay_exact and scalar(@{$rec->matches}) == 1 ) {
1031                 
1032                 # caller says to overlay if there is an /exact/ match
1033                 # $auto_overlay_func only proceeds and returns true on exact matches
1034
1035                 my $res = $e->json_query(
1036                     {
1037                         from => [
1038                             $auto_overlay_func,
1039                             $rec_id,
1040                             $merge_profile
1041                         ]
1042                     }
1043                 );
1044
1045                 if($res and ($res = $res->[0])) {
1046
1047                     if($res->{$auto_overlay_func} eq 't') {
1048                         $logger->info("vl: $type auto-overlay succeeded for queued rec $rec_id");
1049                         $imported = 1;
1050
1051                         # re-fetch the record to pick up the imported_as value from the DB
1052                         $$report_args{rec} = $rec = $e->$retrieve_func([
1053                             $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1054
1055                     } else {
1056                         $logger->info("vl: $type auto-overlay failed for queued rec $rec_id");
1057                     }
1058
1059                 } else {
1060                     $error = 1;
1061                     $logger->error("vl: Error attempting overlay with func=$auto_overlay_func, profile=$merge_profile, record=$rec_id");
1062                 }
1063             }
1064
1065             if(!$imported and !$error and $auto_overlay_best and scalar(@{$rec->matches}) > 0 ) {
1066
1067                 # caller says to overlay the best match
1068
1069                 my $res = $e->json_query(
1070                     {
1071                         from => [
1072                             $auto_overlay_best_func,
1073                             $rec_id,
1074                             $merge_profile,
1075                             $match_quality_ratio
1076                         ]
1077                     }
1078                 );
1079
1080                 if($res and ($res = $res->[0])) {
1081
1082                     if($res->{$auto_overlay_best_func} eq 't') {
1083                         $logger->info("vl: $type auto-overlay-best succeeded for queued rec $rec_id");
1084                         $imported = 1;
1085
1086                         # re-fetch the record to pick up the imported_as value from the DB
1087                         $$report_args{rec} = $rec = $e->$retrieve_func([
1088                             $rec_id, {flesh => 1, flesh_fields => {$rec_class => ['matches']}}]);
1089
1090                     } else {
1091                         $$report_args{import_error} = 'overlay.record.quality' if $match_quality_ratio > 0;
1092                         $logger->info("vl: $type auto-overlay-best failed for queued rec $rec_id");
1093                     }
1094
1095                 } else {
1096                     $error = 1;
1097                     $logger->error("vl: Error attempting overlay with func=$auto_overlay_best_func, ".
1098                         "quality_ratio=$match_quality_ratio, profile=$merge_profile, record=$rec_id");
1099                 }
1100             }
1101
1102             if(!$imported and !$error and $import_no_match and scalar(@{$rec->matches}) == 0) {
1103             
1104                 # No overlay / merge occurred.  Do a traditional record import by creating a new record
1105             
1106                 $logger->info("vl: creating new $type record for queued record $rec_id");
1107                 if($type eq 'bib') {
1108                     $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
1109                         $e, $rec->marc, $bib_sources{$rec->bib_source}, undef, 1);
1110                 } else {
1111
1112                     $record = OpenILS::Application::Cat::AuthCommon->import_authority_record($e, $rec->marc); #$source);
1113                 }
1114
1115                 if($U->event_code($record)) {
1116                     $$report_args{import_error} = 'import.duplicate.tcn' 
1117                         if $record->{textcode} eq 'OPEN_TCN_NOT_FOUND';
1118                     $$report_args{evt} = $record;
1119
1120                 } else {
1121
1122                     $logger->info("vl: successfully imported new $type record");
1123                     $rec->imported_as($record->id);
1124                     $imported = 1;
1125                 }
1126             }
1127         }
1128
1129         if($imported) {
1130
1131             $rec->import_time('now');
1132             $rec->clear_import_error;
1133             $rec->clear_error_detail;
1134
1135             if($e->$update_func($rec)) {
1136
1137                 push @success_rec_ids, $rec_id;
1138                 finish_rec_import_attempt($report_args);
1139
1140             } else {
1141                 $imported = 0;
1142             }
1143         }
1144
1145         if(!$imported) {
1146             $logger->info("vl: record $rec_id was not imported");
1147             $$report_args{evt} = $e->event unless $$report_args{evt};
1148             finish_rec_import_attempt($report_args);
1149         }
1150     }
1151
1152     # see if we need to mark any queues as complete
1153     for my $q_id (keys %queues) {
1154
1155         my $e = new_editor(xact => 1);
1156         my $remaining = $e->$search_func(
1157             [{queue => $q_id, import_time => undef}, {limit =>1}], {idlist => 1});
1158
1159         unless(@$remaining) {
1160             my $queue = $e->$retrieve_queue_func($q_id);
1161
1162             unless($U->is_true($queue->complete)) {
1163                 $queue->complete('t');
1164                 $e->$update_queue_func($queue) or return $e->die_event;
1165                 $e->commit;
1166                 next;
1167             }
1168         } 
1169         $e->rollback;
1170     }
1171
1172     # import the copies
1173     import_record_asset_list_impl($conn, \@success_rec_ids, $requestor) if @success_rec_ids;
1174
1175     $conn->respond({total => $$report_args{total}, progress => $$report_args{progress}});
1176     return undef;
1177 }
1178
1179 # tracks any import errors, commits the current xact, responds to the client
1180 sub finish_rec_import_attempt {
1181     my $args = shift;
1182     my $evt = $$args{evt};
1183     my $rec = $$args{rec};
1184     my $e = $$args{e};
1185
1186     my $error = $$args{import_error};
1187     $error = 'general.unknown' if $evt and not $error;
1188
1189     # error tracking
1190     if($rec) {
1191
1192         if($error or $evt) {
1193             # failed import
1194             # since an error occurred, there's no guarantee the transaction wasn't 
1195             # rolled back.  force a rollback and create a new editor.
1196             $e->rollback;
1197             $e = new_editor(xact => 1);
1198             $rec->import_error($error);
1199
1200             if($evt) {
1201                 my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 140));
1202                 $rec->error_detail($detail);
1203             }
1204
1205             my $method = 'update_vandelay_queued_bib_record';
1206             $method =~ s/bib/authority/ if $$args{type} eq 'auth';
1207             $e->$method($rec) and $e->commit or $e->rollback;
1208
1209         } else {
1210             # commit the successful import
1211             $e->commit;
1212         }
1213
1214     } else {
1215         # requested queued record was not found
1216         $e->rollback;
1217     }
1218         
1219     # respond to client
1220     if($$args{report_all} or ($$args{progress} % $$args{step}) == 0) {
1221         $$args{conn}->respond({
1222             total => $$args{total}, 
1223             progress => $$args{progress}, 
1224             imported => ($rec) ? $rec->id : undef,
1225             err_event => $evt
1226         });
1227         $$args{step} *= 2 unless $$args{step} == 256;
1228     }
1229
1230     $$args{progress}++;
1231 }
1232
1233
1234
1235
1236
1237 __PACKAGE__->register_method(  
1238     api_name    => "open-ils.vandelay.bib_queue.owner.retrieve",
1239     method      => 'owner_queue_retrieve',
1240     api_level   => 1,
1241     argc        => 2,
1242     stream      => 1,
1243     record_type => 'bib'
1244 );
1245 __PACKAGE__->register_method(  
1246     api_name    => "open-ils.vandelay.authority_queue.owner.retrieve",
1247     method      => 'owner_queue_retrieve',
1248     api_level   => 1,
1249     argc        => 2,
1250     stream      => 1,
1251     record_type => 'auth'
1252 );
1253
1254 sub owner_queue_retrieve {
1255     my($self, $conn, $auth, $owner_id, $filters) = @_;
1256     my $e = new_editor(authtoken => $auth, xact => 1);
1257     return $e->die_event unless $e->checkauth;
1258     $owner_id = $e->requestor->id; # XXX add support for viewing other's queues?
1259     my $queues;
1260     $filters ||= {};
1261     my $search = {owner => $owner_id};
1262     $search->{$_} = $filters->{$_} for keys %$filters;
1263
1264     if($self->{record_type} eq 'bib') {
1265         $queues = $e->search_vandelay_bib_queue(
1266             [$search, {order_by => {vbq => 'evergreen.lowercase(name)'}}]);
1267     } else {
1268         $queues = $e->search_vandelay_authority_queue(
1269             [$search, {order_by => {vaq => 'evergreen.lowercase(name)'}}]);
1270     }
1271     $conn->respond($_) for @$queues;
1272     $e->rollback;
1273     return undef;
1274 }
1275
1276 __PACKAGE__->register_method(  
1277     api_name    => "open-ils.vandelay.bib_queue.delete",
1278     method      => "delete_queue",
1279     api_level   => 1,
1280     argc        => 2,
1281     record_type => 'bib'
1282 );            
1283 __PACKAGE__->register_method(  
1284     api_name    => "open-ils.vandelay.auth_queue.delete",
1285     method      => "delete_queue",
1286     api_level   => 1,
1287     argc        => 2,
1288     record_type => 'auth'
1289 );  
1290
1291 sub delete_queue {
1292     my($self, $conn, $auth, $q_id) = @_;
1293     my $e = new_editor(xact => 1, authtoken => $auth);
1294     return $e->die_event unless $e->checkauth;
1295     if($self->{record_type} eq 'bib') {
1296         return $e->die_event unless $e->allowed('CREATE_BIB_IMPORT_QUEUE');
1297         my $queue = $e->retrieve_vandelay_bib_queue($q_id)
1298             or return $e->die_event;
1299         $e->delete_vandelay_bib_queue($queue)
1300             or return $e->die_event;
1301     } else {
1302            return $e->die_event unless $e->allowed('CREATE_AUTHORITY_IMPORT_QUEUE');
1303         my $queue = $e->retrieve_vandelay_authority_queue($q_id)
1304             or return $e->die_event;
1305         $e->delete_vandelay_authority_queue($queue)
1306             or return $e->die_event;
1307     }
1308     $e->commit;
1309     return 1;
1310 }
1311
1312
1313 __PACKAGE__->register_method(  
1314     api_name    => "open-ils.vandelay.queued_bib_record.html",
1315     method      => 'queued_record_html',
1316     api_level   => 1,
1317     argc        => 2,
1318     stream      => 1,
1319     record_type => 'bib'
1320 );
1321 __PACKAGE__->register_method(  
1322     api_name    => "open-ils.vandelay.queued_authority_record.html",
1323     method      => 'queued_record_html',
1324     api_level   => 1,
1325     argc        => 2,
1326     stream      => 1,
1327     record_type => 'auth'
1328 );
1329
1330 sub queued_record_html {
1331     my($self, $conn, $auth, $rec_id) = @_;
1332     my $e = new_editor(xact=>1,authtoken => $auth);
1333     return $e->die_event unless $e->checkauth;
1334     my $rec;
1335     if($self->{record_type} eq 'bib') {
1336         $rec = $e->retrieve_vandelay_queued_bib_record($rec_id)
1337             or return $e->die_event;
1338     } else {
1339         $rec = $e->retrieve_vandelay_queued_authority_record($rec_id)
1340             or return $e->die_event;
1341     }
1342
1343     $e->rollback;
1344     return $U->simplereq(
1345         'open-ils.search',
1346         'open-ils.search.biblio.record.html', undef, 1, $rec->marc);
1347 }
1348
1349
1350 __PACKAGE__->register_method(  
1351     api_name    => "open-ils.vandelay.bib_queue.summary.retrieve", 
1352     method      => 'retrieve_queue_summary',
1353     api_level   => 1,
1354     argc        => 2,
1355     stream      => 1,
1356     record_type => 'bib'
1357 );
1358 __PACKAGE__->register_method(  
1359     api_name    => "open-ils.vandelay.auth_queue.summary.retrieve",
1360     method      => 'retrieve_queue_summary',
1361     api_level   => 1,
1362     argc        => 2,
1363     stream      => 1,
1364     record_type => 'auth'
1365 );
1366
1367 sub retrieve_queue_summary {
1368     my($self, $conn, $auth, $queue_id) = @_;
1369     my $e = new_editor(xact=>1, authtoken => $auth);
1370     return $e->die_event unless $e->checkauth;
1371
1372     my $queue;
1373     my $type = $self->{record_type};
1374     if($type eq 'bib') {
1375         $queue = $e->retrieve_vandelay_bib_queue($queue_id)
1376             or return $e->die_event;
1377     } else {
1378         $queue = $e->retrieve_vandelay_authority_queue($queue_id)
1379             or return $e->die_event;
1380     }
1381
1382     my $evt = check_queue_perms($e, $type, $queue);
1383     return $evt if $evt;
1384
1385     my $search = 'search_vandelay_queued_bib_record';
1386     $search =~ s/bib/authority/ if $type ne 'bib';
1387
1388     my $summary = {
1389         queue => $queue,
1390         total => scalar(@{$e->$search({queue => $queue_id}, {idlist=>1})}),
1391         imported => scalar(@{$e->$search({queue => $queue_id, import_time => {'!=' => undef}}, {idlist=>1})}),
1392     };
1393
1394     my $class = ($type eq 'bib') ? 'vqbr' : 'vqar';
1395     $summary->{rec_import_errors} = $e->json_query({
1396         select => {$class => [{alias => 'count', column => 'id', transform => 'count', aggregate => 1}]},
1397         from => $class,
1398         where => {queue => $queue_id, import_error => {'!=' => undef}}
1399     })->[0]->{count};
1400
1401     if($type eq 'bib') {
1402         
1403         # count of all items attached to records in the queue in question
1404         my $query = {
1405             select => {vii => [{alias => 'count', column => 'id', transform => 'count', aggregate => 1}]},
1406             from => 'vii',
1407             where => {
1408                 record => {
1409                     in => {
1410                         select => {vqbr => ['id']},
1411                         from => 'vqbr',
1412                         where => {queue => $queue_id}
1413                     }
1414                 }
1415             }
1416         };
1417         $summary->{total_items} = $e->json_query($query)->[0]->{count};
1418
1419         # count of items we attempted to import, but errored, attached to records in the queue in question
1420         $query->{where}->{import_error} = {'!=' => undef};
1421         $summary->{item_import_errors} = $e->json_query($query)->[0]->{count};
1422
1423         # count of items we successfully imported attached to records in the queue in question
1424         delete $query->{where}->{import_error};
1425         $query->{where}->{import_time} = {'!=' => undef};
1426         $summary->{total_items_imported} = $e->json_query($query)->[0]->{count};
1427     }
1428
1429     return $summary;
1430 }
1431
1432 # --------------------------------------------------------------------------------
1433 # Given a list of queued record IDs, imports all items attached to those records
1434 # --------------------------------------------------------------------------------
1435 sub import_record_asset_list_impl {
1436     my($conn, $rec_ids, $requestor) = @_;
1437
1438     my $roe = new_editor(xact=> 1, requestor => $requestor);
1439
1440     # for speed, filter out any records have not been 
1441     # imported or have no import items to load
1442     $rec_ids = $roe->json_query({
1443         select => {vqbr => ['id']},
1444         from => {vqbr => 'vii'},
1445         where => {'+vqbr' => {
1446             id => $rec_ids,
1447             import_time => {'!=' => undef}
1448         }},
1449         distinct => 1
1450     });
1451     $rec_ids = [map {$_->{id}} @$rec_ids];
1452
1453     my $report_args = {
1454         conn => $conn,
1455         total => scalar(@$rec_ids),
1456         step => 1, # how often to respond
1457         progress => 1,
1458         in_count => 0,
1459     };
1460
1461     for my $rec_id (@$rec_ids) {
1462         my $rec = $roe->retrieve_vandelay_queued_bib_record($rec_id);
1463         my $item_ids = $roe->search_vandelay_import_item({record => $rec->id}, {idlist=>1});
1464
1465         for my $item_id (@$item_ids) {
1466             my $e = new_editor(requestor => $requestor, xact => 1);
1467             my $item = $e->retrieve_vandelay_import_item($item_id);
1468             $$report_args{import_item} = $item;
1469             $$report_args{e} = $e;
1470             $$report_args{import_error} = undef;
1471             $$report_args{evt} = undef;
1472
1473             # --------------------------------------------------------------------------------
1474             # Find or create the volume
1475             # --------------------------------------------------------------------------------
1476             my ($vol, $evt) =
1477                 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1478                     $e, $item->call_number, $rec->imported_as, $item->owning_lib);
1479
1480             if($evt) {
1481
1482                 $$report_args{evt} = $evt;
1483                 respond_with_status($report_args);
1484                 next;
1485             }
1486
1487             # --------------------------------------------------------------------------------
1488             # Create the new copy
1489             # --------------------------------------------------------------------------------
1490             my $copy = Fieldmapper::asset::copy->new;
1491             $copy->loan_duration(2);
1492             $copy->fine_level(2);
1493             $copy->barcode($item->barcode);
1494             $copy->location($item->location);
1495             $copy->circ_lib($item->circ_lib || $item->owning_lib);
1496             $copy->status( defined($item->status) ? $item->status : OILS_COPY_STATUS_IN_PROCESS );
1497             $copy->circulate($item->circulate);
1498             $copy->deposit($item->deposit);
1499             $copy->deposit_amount($item->deposit_amount);
1500             $copy->ref($item->ref);
1501             $copy->holdable($item->holdable);
1502             $copy->price($item->price);
1503             $copy->circ_as_type($item->circ_as_type);
1504             $copy->alert_message($item->alert_message);
1505             $copy->opac_visible($item->opac_visible);
1506             $copy->circ_modifier($item->circ_modifier);
1507
1508             # --------------------------------------------------------------------------------
1509             # see if a valid circ_modifier was provided
1510             # --------------------------------------------------------------------------------
1511             if($copy->circ_modifier and not $e->search_config_circ_modifier({code=>$item->circ_modifier})->[0]) {
1512                 $$report_args{evt} = $e->die_event;
1513                 $$report_args{import_error} = 'import.item.invalid.circ_modifier';
1514                 respond_with_status($report_args);
1515                 next;
1516             }
1517
1518             if($copy->location and not $e->retrieve_asset_copy_location($copy->location)) {
1519                 $$report_args{evt} = $e->die_event;
1520                 $$report_args{import_error} = 'import.item.invalid.location';
1521                 respond_with_status($report_args);
1522                 next;
1523             }
1524
1525             if($evt = OpenILS::Application::Cat::AssetCommon->create_copy($e, $vol, $copy)) {
1526                 $$report_args{evt} = $evt;
1527                 $$report_args{import_error} = 'import.item.duplicate.barcode'
1528                     if $evt->{textcode} eq 'ITEM_BARCODE_EXISTS';
1529                 respond_with_status($report_args);
1530                 next;
1531             }
1532
1533             # --------------------------------------------------------------------------------
1534             # create copy notes
1535             # --------------------------------------------------------------------------------
1536             $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1537                 $e, $copy, '', $item->pub_note, 1) if $item->pub_note;
1538
1539             if($evt) {
1540                 $$report_args{evt} = $evt;
1541                 respond_with_status($report_args);
1542                 next;
1543             }
1544
1545             $evt = OpenILS::Application::Cat::AssetCommon->create_copy_note(
1546                 $e, $copy, '', $item->priv_note) if $item->priv_note;
1547
1548             if($evt) {
1549                 $$report_args{evt} = $evt;
1550                 respond_with_status($report_args);
1551                 next;
1552             }
1553
1554             # set the import data on the import item
1555             $item->imported_as($copy->id); # $copy->id is set by create_copy() ^--
1556             $item->import_time('now');
1557
1558             unless($e->update_vandelay_import_item($item)) {
1559                 $$report_args{evt} = $e->die_event;
1560                 respond_with_status($report_args);
1561                 next;
1562             }
1563
1564             # --------------------------------------------------------------------------------
1565             # Item import succeeded
1566             # --------------------------------------------------------------------------------
1567             $e->commit;
1568             $$report_args{in_count}++;
1569             respond_with_status($report_args);
1570             $logger->info("vl: successfully imported item " . $item->barcode);
1571         }
1572
1573     }
1574
1575     $roe->rollback;
1576     return undef;
1577 }
1578
1579
1580 sub respond_with_status {
1581     my $args = shift;
1582     my $e = $$args{e};
1583
1584     #  If the import failed, track the failure reason
1585
1586     my $error = $$args{import_error};
1587     my $evt = $$args{evt};
1588
1589     if($error or $evt) {
1590
1591         my $item = $$args{import_item};
1592         $logger->info("vl: unable to import item " . $item->barcode);
1593
1594         $error ||= 'general.unknown';
1595         $item->import_error($error);
1596
1597         if($evt) {
1598             my $detail = sprintf("%s : %s", $evt->{textcode}, substr($evt->{desc}, 0, 140));
1599             $item->error_detail($detail);
1600         }
1601
1602         # state of the editor is unknown at this point.  Force a rollback and start over.
1603         $e->rollback;
1604         $e = new_editor(xact => 1);
1605         $e->update_vandelay_import_item($item);
1606         $e->commit;
1607     }
1608
1609     if($$args{report_all} or ($$args{progress} % $$args{step}) == 0) {
1610         $$args{conn}->respond({
1611             total => $$args{total},
1612             progress => $$args{progress},
1613             success_count => $$args{success_count},
1614             err_event => $evt
1615         });
1616         $$args{step} *= 2 unless $$args{step} == 256;
1617     }
1618
1619     $$args{progress}++;
1620 }
1621
1622 __PACKAGE__->register_method(  
1623     api_name    => "open-ils.vandelay.match_set.get_tree",
1624     method      => "match_set_get_tree",
1625     api_level   => 1,
1626     argc        => 2,
1627     signature   => {
1628         desc    => q/For a given vms object, return a tree of match set points
1629                     represented by a vmsp object with recursively fleshed
1630                     children./
1631     }
1632 );
1633
1634 sub match_set_get_tree {
1635     my ($self, $conn, $authtoken, $match_set_id) = @_;
1636
1637     $match_set_id = int($match_set_id) or return;
1638
1639     my $e = new_editor("authtoken" => $authtoken);
1640     $e->checkauth or return $e->die_event;
1641
1642     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1643         return $e->die_event;
1644
1645     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1646         return $e->die_event;
1647
1648     my $tree = $e->search_vandelay_match_set_point([
1649         {"match_set" => $match_set_id, "parent" => undef},
1650         {"flesh" => -1, "flesh_fields" => {"vmsp" => ["children"]}}
1651     ]) or return $e->die_event;
1652
1653     return pop @$tree;
1654 }
1655
1656
1657 __PACKAGE__->register_method(
1658     api_name    => "open-ils.vandelay.match_set.update",
1659     method      => "match_set_update_tree",
1660     api_level   => 1,
1661     argc        => 3,
1662     signature   => {
1663         desc => q/Replace any vmsp objects associated with a given (by ID) vms
1664                 with the given objects (recursively fleshed vmsp tree)./
1665     }
1666 );
1667
1668 sub _walk_new_vmsp {
1669     my ($e, $match_set_id, $node, $parent_id) = @_;
1670
1671     my $point = new Fieldmapper::vandelay::match_set_point;
1672     $point->parent($parent_id);
1673     $point->match_set($match_set_id);
1674     $point->$_($node->$_) for (qw/bool_op svf tag subfield negate quality/);
1675
1676     $e->create_vandelay_match_set_point($point) or return $e->die_event;
1677
1678     $parent_id = $e->data->id;
1679     if ($node->children && @{$node->children}) {
1680         for (@{$node->children}) {
1681             return $e->die_event if
1682                 _walk_new_vmsp($e, $match_set_id, $_, $parent_id);
1683         }
1684     }
1685
1686     return;
1687 }
1688
1689 sub match_set_update_tree {
1690     my ($self, $conn, $authtoken, $match_set_id, $tree) = @_;
1691
1692     my $e = new_editor("xact" => 1, "authtoken" => $authtoken);
1693     $e->checkauth or return $e->die_event;
1694
1695     my $set = $e->retrieve_vandelay_match_set($match_set_id) or
1696         return $e->die_event;
1697
1698     $e->allowed("ADMIN_IMPORT_MATCH_SET", $set->owner) or
1699         return $e->die_event;
1700
1701     my $existing = $e->search_vandelay_match_set_point([
1702         {"match_set" => $match_set_id},
1703         {"order_by" => {"vmsp" => "id DESC"}}
1704     ]) or return $e->die_event;
1705
1706     # delete points, working up from leaf points to the root
1707     while(@$existing) {
1708         for my $point (shift @$existing) {
1709             if( grep {$_->parent eq $point->id} @$existing) {
1710                 push(@$existing, $point);
1711             } else {
1712                 $e->delete_vandelay_match_set_point($point) or return $e->die_event;
1713             }
1714         }
1715     }
1716
1717     _walk_new_vmsp($e, $match_set_id, $tree);
1718
1719     $e->commit or return $e->die_event;
1720 }
1721
1722 1;