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