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