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