]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Acq/EDI.pm
EDI response honor lineitem-level status; debit cleanup
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Acq / EDI.pm
1 package OpenILS::Application::Acq::EDI;
2 use base qw/OpenILS::Application/;
3
4 use strict; use warnings;
5
6 use IO::Scalar;
7
8 use OpenSRF::AppSession;
9 use OpenSRF::EX qw/:try/;
10 use OpenSRF::Utils::Logger qw(:logger);
11 use OpenSRF::Utils::JSON;
12
13 use OpenILS::Application::Acq::Lineitem;
14 use OpenILS::Utils::RemoteAccount;
15 use OpenILS::Utils::CStoreEditor q/new_editor/;
16 use OpenILS::Utils::Fieldmapper;
17 use OpenILS::Application::Acq::EDI::Translator;
18 use OpenILS::Application::AppUtils;
19 my $U = 'OpenILS::Application::AppUtils';
20
21 use OpenILS::Utils::EDIReader;
22
23 use Data::Dumper;
24 our $verbose = 0;
25
26 sub new {
27     my($class, %args) = @_;
28     my $self = bless(\%args, $class);
29     # $self->{args} = {};
30     return $self;
31 }
32
33 # our $reasons = {};   # cache for acq.cancel_reason rows ?
34
35 our $translator;
36
37 sub translator {
38     return $translator ||= OpenILS::Application::Acq::EDI::Translator->new(@_);
39 }
40
41 my %map = (
42     host     => 'remote_host',
43     username => 'remote_user',
44     password => 'remote_password',
45     account  => 'remote_account',
46     # in_dir   => 'remote_path',   # field_map overrides path with in_dir
47     path     => 'remote_path',
48 );
49
50
51 ## Just for debugging stuff:
52 sub add_a_msg {
53     my ($self, $conn) = @_;
54     my $e = new_editor(xact=>1);
55     my $incoming = Fieldmapper::acq::edi_message->new;
56     $incoming->edi("This is content");
57     $incoming->account(1);
58     $incoming->remote_file('in/some_file.edi');
59     $e->create_acq_edi_message($incoming);;
60     $e->commit;
61 }
62 # __PACKAGE__->register_method( method => 'add_a_msg', api_name => 'open-ils.acq.edi.add_a_msg');  # debugging
63
64 __PACKAGE__->register_method(
65         method    => 'retrieve',
66         api_name  => 'open-ils.acq.edi.retrieve',
67     authoritative => 1,
68         signature => {
69         desc   => 'Fetch incoming message(s) from EDI accounts.  ' .
70                   'Optional arguments to restrict to one vendor and/or a max number of messages.  ' .
71                   'Note that messages are not parsed or processed here, just fetched and translated.',
72         params => [
73             {desc => 'Authentication token',        type => 'string'},
74             {desc => 'Vendor ID (undef for "all")', type => 'number'},
75             {desc => 'Date Inactive Since',         type => 'string'},
76             {desc => 'Max Messages Retrieved',      type => 'number'}
77         ],
78         return => {
79             desc => 'List of new message IDs (empty if none)',
80             type => 'array'
81         }
82     }
83 );
84
85 sub retrieve_core {
86     my ($self, $set, $max, $e, $test) = @_;    # $e is a working editor
87
88     $e   ||= new_editor();
89     $set ||= __PACKAGE__->retrieve_vendors($e);
90
91     my @return = ();
92     my $vcount = 0;
93     foreach my $account (@$set) {
94         my $count = 0;
95         my $server;
96         $logger->info("EDI check for vendor " . ++$vcount . " of " . scalar(@$set) . ": " . $account->host);
97         unless ($server = __PACKAGE__->remote_account($account)) {   # assignment, not comparison
98             $logger->err(sprintf "Failed remote account mapping for %s (%s)", $account->host, $account->id);
99             next;
100         };
101 #       my $rf_starter = './';  # default to current dir
102         if ($account->in_dir) { 
103             if ($account->in_dir =~ /\*+.*\//) {
104                 $logger->err("EDI in_dir has a slash after an asterisk in value: '" . $account->in_dir . "'.  Skipping account with indeterminate target dir!");
105                 next;
106             }
107 #           $rf_starter = $account->in_dir;
108 #           $rf_starter =~ s/((\/)?[^\/]*)\*+[^\/]*$//;  # kill up to the first (possible) slash before the asterisk: keep the preceeding static dir
109 #           $rf_starter .= '/' if $rf_starter or $2;   # recap the dir, or replace leading "/" if there was one (but don't add if empty)
110         }
111         my @files    = ($server->ls({remote_file => ($account->in_dir || './')}));
112         my @ok_files = grep {$_ !~ /\/\.?\.$/ and $_ ne '0'} @files;
113         $logger->info(sprintf "%s of %s files at %s/%s", scalar(@ok_files), scalar(@files), $account->host, $account->in_dir);   
114         # $server->remote_path(undef);
115         foreach my $remote_file (@ok_files) {
116             # my $remote_file = $rf_starter . $_;
117             my $description = sprintf "%s/%s", $account->host, $remote_file;
118             
119             # deduplicate vs. acct/filenames already in DB
120             my $hits = $e->search_acq_edi_message([
121                 {
122                     account     => $account->id,
123                     remote_file => $remote_file,
124                     status      => {'in' => [qw/ processed /]},     # if it never got processed, go ahead and get the new one (try again)
125                     # create_time => 'NOW() - 60 DAYS',     # if we wanted to allow filenames to be reused after a certain time
126                     # ideally we would also use the date from FTP, but that info isn't available via RemoteAccount
127                 }
128                 # { flesh => 1, flesh_fields => {...}, }
129             ]);
130             if (scalar(@$hits)) {
131                 $logger->debug("EDI: $remote_file already retrieved.  Skipping");
132                 warn "EDI: $remote_file already retrieved.  Skipping";
133                 next;
134             }
135
136             ++$count;
137             $max and $count > $max and last;
138             $logger->info(sprintf "%s of %s targets: %s", $count, scalar(@ok_files), $description);
139             print sprintf "%s of %s targets: %s\n", $count, scalar(@ok_files), $description;
140             if ($test) {
141                 push @return, "test_$count";
142                 next;
143             }
144             my $content;
145             my $io = IO::Scalar->new(\$content);
146             unless ( $server->get({remote_file => $remote_file, local_file => $io}) ) {
147                 $logger->error("(S)FTP get($description) failed");
148                 next;
149             }
150             my $incoming = __PACKAGE__->process_retrieval($content, $remote_file, $server, $account->id);
151 #           $server->delete(remote_file => $_);   # delete remote copies of saved message
152             push @return, @$incoming;
153         }
154     }
155     return \@return;
156 }
157
158 # my $msg_ids = OpenILS::Application::Acq::EDI->process_retrieval(
159 #   $file_content, $remote_filename, $server, $account_id, $editor);
160
161 sub process_retrieval {
162     my ($class, $content, $filename, $server, $account_or_id) = @_;
163     $content or return;
164
165     my $e = new_editor;
166     my $account = __PACKAGE__->record_activity($account_or_id, $e);
167
168     # a single EDI blob can contain multiple messages
169     # create one edi_message per included message
170
171     my $messages = OpenILS::Utils::EDIReader->new->read($content);
172     my @return;
173
174     for my $msg_hash (@$messages) {
175
176         my $incoming = Fieldmapper::acq::edi_message->new;
177
178         $incoming->remote_file($filename);
179         $incoming->account($account->id);
180         $incoming->edi($content);
181         $incoming->message_type($msg_hash->{message_type});
182         $incoming->jedi(OpenSRF::Utils::JSON->perl2JSON($msg_hash)); # jedi-2.0
183         $incoming->status('translated');
184         $incoming->translate_time('NOW');
185
186         if ($msg_hash->{purchase_order}) {
187             $logger->info("EDI: processing message for PO " . $msg_hash->{purchase_order});
188             $incoming->purchase_order($msg_hash->{purchase_order});
189             unless ($e->retrieve_acq_purchase_order($incoming->purchase_order)) {
190                 $logger->warn("EDI: received order response for nonexistent PO.  Skipping...");
191                 next;
192             }
193         }
194
195         $e->xact_begin;
196         unless($e->create_acq_edi_message($incoming)) {
197             $logger->error("EDI: unable to create edi_message " . $e->die_event);
198             next;
199         }
200         # refresh to pickup create_date, etc.
201         $incoming = $e->retrieve_acq_edi_message($incoming->id);
202         $e->xact_commit;
203
204         # since there's a fair chance of unhandled problems 
205         # cropping up, particularly with new vendors, wrap w/ eval.
206         eval { $class->process_parsed_msg($account, $incoming, $msg_hash) };
207
208         $e->xact_begin;
209         $incoming = $e->retrieve_acq_edi_message($incoming->id);
210         if ($@) {
211             $incoming->status('proc_error');
212             $incoming->error($@);
213         } else {
214             $incoming->status('processed');
215         }
216         $e->update_acq_edi_message($incoming);
217         $e->xact_commit;
218
219         push(@return, $incoming->id);
220     }
221
222     return \@return;
223 }
224
225 # ->send_core
226 # $account     is a Fieldmapper object for acq.edi_account row
227 # $messageset  is an arrayref with acq.edi_message.id values
228 # $e           is optional editor object
229 sub send_core {
230     my ($class, $account, $message_ids, $e) = @_;    # $e is a working editor
231
232     ($account and scalar @$message_ids) or return;
233     $e ||= new_editor();
234
235     $e->xact_begin;
236     my @messageset = map {$e->retrieve_acq_edi_message($_)} @$message_ids;
237     $e->xact_rollback;
238     my $m_count = scalar(@messageset);
239     (scalar(@$message_ids) == $m_count) or
240         $logger->warn(scalar(@$message_ids) - $m_count . " bad IDs passed to send_core (ignored)");
241
242     my $log_str = sprintf "EDI send to edi_account %s (%s)", $account->id, $account->host;
243     $logger->info("$log_str: $m_count message(s)");
244     $m_count or return;
245
246     my $server;
247     my $server_error;
248     unless ($server = __PACKAGE__->remote_account($account, 1)) {   # assignment, not comparison
249         $logger->error("Failed remote account connection for $log_str");
250         $server_error = 1;
251     };
252     foreach (@messageset) {
253         $_ or next;     # we already warned about bum ids
254         my ($res, $error);
255         if ($server_error) {
256             $error = "Server error: Failed remote account connection for $log_str"; # already told $logger, this is to update object below
257         } elsif (! $_->edi) {
258             $logger->error("Message (id " . $_->id. ") for $log_str has no EDI content");
259             $error = "EDI empty!";
260         } elsif ($res = $server->put({remote_path => $account->path, content => $_->edi, single_ext => 1})) {
261             #  This is the successful case!
262             $_->remote_file($res);
263             $_->status('complete');
264             $_->process_time('NOW');    # For outbound files, sending is the end of processing on the EG side.
265             $logger->info("Sent message (id " . $_->id. ") via $log_str");
266         } else {
267             $logger->error("(S)FTP put to $log_str FAILED: " . ($server->error || 'UNKOWNN'));
268             $error = "put FAILED: " . ($server->error || 'UNKOWNN');
269         }
270         if ($error) {
271             $_->error($error);
272             $_->error_time('NOW');
273         }
274         $logger->info("Calling update_acq_edi_message");
275         $e->xact_begin;
276         unless ($e->update_acq_edi_message($_)) {
277              $logger->error("EDI send_core update_acq_edi_message failed for message object: " . Dumper($_));
278              OpenILS::Application::Acq::EDI::Translator->debug_file(Dumper($_              ), '/tmp/update_acq_edi_message.FAIL');
279              OpenILS::Application::Acq::EDI::Translator->debug_file(Dumper($_->to_bare_hash), '/tmp/update_acq_edi_message.FAIL.to_bare_hash');
280         }
281         # There's always an update, even if we failed.
282         $e->xact_commit;
283         __PACKAGE__->record_activity($account, $e);  # There's always an update, even if we failed.
284     }
285     return \@messageset;
286 }
287
288 #  attempt_translation does not touch the DB, just the object.  
289 sub attempt_translation {
290     my ($class, $edi_message, $to_edi) = @_;
291     my $tran  = translator();
292     my $ret   = $to_edi ? $tran->json2edi($edi_message->jedi) : $tran->edi2json($edi_message->edi);
293 #   $logger->error("json: " . Dumper($json)); # debugging
294
295     if (not $ret or (! ref($ret)) or $ret->is_fault) {      # RPC::XML::fault on failure
296         $edi_message->status('trans_error');
297         $edi_message->error_time('NOW');
298         my $pre = "EDI Translator " . ($to_edi ? 'json2edi' : 'edi2json') . " failed";
299         my $message = ref($ret) ? 
300                       ("$pre, Error " . $ret->code . ": " . __PACKAGE__->nice_string($ret->string)) :
301                       ("$pre: "                           . __PACKAGE__->nice_string($ret)        ) ;
302         $edi_message->error($message);
303         $logger->error($message);
304         return;
305     }
306
307     $edi_message->status('translated');
308     $edi_message->translate_time('NOW');
309
310     if ($to_edi) {
311         $edi_message->edi($ret->value);    # translator returns an object
312     } else {
313         $edi_message->jedi($ret->value);   # translator returns an object
314     }
315     return $edi_message;
316 }
317
318 sub retrieve_vendors {
319     my ($self, $e, $vendor_id, $last_activity) = @_;    # $e is a working editor
320
321     $e ||= new_editor();
322
323     my $criteria = {'+acqpro' => {active => 't'}};
324     $criteria->{'+acqpro'}->{id} = $vendor_id if $vendor_id;
325     return $e->search_acq_edi_account([
326         $criteria, {
327             'join' => 'acqpro',
328             flesh => 1,
329             flesh_fields => {
330                 acqedi => ['provider']
331             }
332         }
333     ]);
334 #   {"id":{"!=":null},"+acqpro":{"active":"t"}}, {"join":"acqpro", "flesh_fields":{"acqedi":["provider"]},"flesh":1}
335 }
336
337 # This is the SRF-exposed call, so it does checkauth
338
339 sub retrieve {
340     my ($self, $conn, $auth, $vendor_id, $last_activity, $max) = @_;
341
342     my $e = new_editor(authtoken=>$auth);
343     unless ($e and $e->checkauth()) {
344         $logger->warn("checkauth failed for authtoken '$auth'");
345         return ();
346     }
347     # return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);  # add permission here ?
348
349     my $set = __PACKAGE__->retrieve_vendors($e, $vendor_id, $last_activity) or return $e->die_event;
350     return __PACKAGE__->retrieve_core($e, $set, $max);
351 }
352
353
354 # field_map takes the hashref of vendor data with fields from acq.edi_account and 
355 # maps them to the argument style needed for RemoteAccount.  It also extrapolates
356 # data from the remote_host string for type and port, when available.
357
358 sub field_map {
359     my $self   = shift;
360     my $vendor = shift or return;
361     my $no_override = @_ ? shift : 0;
362     my %args = ();
363     $verbose and $logger->warn("vendor: " . Dumper($vendor));
364     foreach (keys %map) {
365         $args{$map{$_}} = $vendor->$_ if defined $vendor->$_;
366     }
367     unless ($no_override) {
368         $args{remote_path} = $vendor->in_dir;    # override "path" with "in_dir"
369     }
370     my $host = $args{remote_host} || '';
371     ($host =~ s/^(S?FTP)://i    and $args{type} = uc($1)) or
372     ($host =~ s/^(SSH|SCP)://i  and $args{type} = 'SCP' ) ;
373      $host =~ s/:(\d+)$//       and $args{port} = $1;
374     ($args{remote_host} = $host) =~ s#/+##;
375     $verbose and $logger->warn("field_map: " . Dumper(\%args));
376     return %args;
377 }
378
379
380 # The point of remote_account is to get the RemoteAccount object with args from the DB
381
382 sub remote_account {
383     my ($self, $vendor, $outbound, $e) = @_;
384
385     unless (ref($vendor)) {     # It's not a hashref/object.
386         $vendor or return;      # If in fact it's nothing: abort!
387                                 # else it's a vendor_id string, so get the full vendor data
388         $e ||= new_editor();
389         my $set_of_one = $self->retrieve_vendors($e, $vendor) or return;
390         $vendor = shift @$set_of_one;
391     }
392
393     return OpenILS::Utils::RemoteAccount->new(
394         $self->field_map($vendor, $outbound)
395     );
396 }
397
398 # takes account ID or account Fieldmapper object
399
400 sub record_activity {
401     my ($class, $account_or_id, $e) = @_;
402     $account_or_id or return;
403     $e ||= new_editor();
404     my $account = ref($account_or_id) ? $account_or_id : $e->retrieve_acq_edi_account($account_or_id);
405     $logger->info("EDI record_activity calling update_acq_edi_account");
406     $account->last_activity('NOW') or return;
407     $e->xact_begin;
408     $e->update_acq_edi_account($account) or $logger->warn("EDI: in record_activity, update_acq_edi_account FAILED");
409     $e->xact_commit;
410     return $account;
411 }
412
413 sub nice_string {
414     my $class = shift;
415     my $string = shift or return '';
416     chomp($string);
417     my $head   = @_ ? shift : 100;
418     my $tail   = @_ ? shift :  25;
419     (length($string) < $head + $tail) and return $string;
420     my $h = substr($string,0,$head);
421     my $t = substr($string, -1*$tail);
422     $h =~s/\s*$//o;
423     $t =~s/\s*$//o;
424     return "$h ... $t";
425     # return substr($string,0,$head) . "... " . substr($string, -1*$tail);
426 }
427
428 # parts of this process can fail without the entire
429 # thing failing.  If a catastrophic error occurs,
430 # it will occur via die.
431 sub process_parsed_msg {
432     my ($class, $account, $incoming, $msg_hash) = @_;
433
434     if ($incoming->message_type eq 'INVOIC') {
435         return $class->create_acq_invoice_from_edi(
436             $msg_hash, $account->provider, $incoming);
437     }
438
439     # ORDRSP
440     for my $li_hash (@{$msg_hash->{lineitems}}) {
441         my $e = new_editor(xact => 1);
442
443         my $li_id = $li_hash->{id};
444         my $li = $e->retrieve_acq_lineitem($li_id);
445
446         if (!$li) {
447             $logger->error("EDI: request for invalid lineitem ID '$li_id'");
448             $e->rollback;
449             next;
450         }
451
452         if ($li_hash->{expected_date}) {
453             my ($y, $m, $d) = $li_hash->{expected_date} =~ /^(\d{4})(\d{2})(\d{2})/g;
454             my $recv_time = $y;
455             $recv_time .= "-$m" if $m;
456             $recv_time .= "-$d" if $d;
457             $li->expected_recv_time($recv_time);
458         }
459
460         $li->estimated_unit_price($li_hash->{unit_price});
461
462         if (not $incoming->purchase_order) {                
463             # PO should come from the EDI message, but if not...
464
465             # fetch the latest copy
466             $incoming = $e->retrieve_acq_edi_message($incoming->id);
467             $incoming->purchase_order($li->purchase_order); 
468
469             unless($e->update_acq_edi_message($incoming)) {
470                 $logger->error("EDI: unable to update edi_message " . $e->die_event);
471                 next;
472             }
473         }
474
475         my $lids = $e->json_query({
476             select => {acqlid => ['id']},
477             from => 'acqlid',
478             where => {lineitem => $li->id}
479         });
480
481         my @lids = map { $_->{id} } @$lids;
482         my $lid_count = scalar(@lids);
483         my $lids_covered = 0;
484         my $lids_cancelled = 0;
485         my $order_qty;
486         my $dispatch_qty;
487   
488         for my $qty (@{$li_hash->{quantities}}) {
489
490             my $qty_count = $qty->{quantity};
491             my $qty_code = $qty->{code};
492
493             next unless defined $qty_count;
494
495             if (!$qty_code) {
496                 $logger->warn("EDI: Response for LI $li_id specifies quantity ".
497                     "$qty_count with no 6063 code! Contact vendor to resolve.");
498                 next;
499             }
500
501             $logger->info("EDI: LI $li_id processing quantity count=$qty_count / code=$qty_code");
502
503             if ($qty_code eq '21') { # "ordered quantity"
504                 $order_qty = $qty_count;
505                 $logger->info("EDI: LI $li_id -- vendor confirms $qty_count ordered");
506                 $logger->warn("EDI: LI $li_id -- order count $qty_count ".
507                     "does not match LID count $lid_count") unless $qty_count == $lid_count;
508                 next;
509             }
510
511             $lids_covered += $qty_count;
512
513             if ($qty_code eq '12') {
514                 $dispatch_qty = $qty_count;
515                 $logger->info("EDI: LI $li_id -- vendor dispatched $qty_count");
516                 next;
517
518             } elsif ($qty_code eq '57') {
519                 $logger->info("EDI: LI $li_id -- $qty_count in transit");
520                 next;
521             }
522             # 84: urgent delivery
523             # 118: quantity manifested
524             # ...
525
526             # -------------------------------------------------------------------------
527             # All of the remaining quantity types require that we apply a cancel_reason
528             # DB populated w/ 6063 keys in 1200's
529
530             my $eg_reason = $e->retrieve_acq_cancel_reason(1200 + $qty_code);  
531
532             if (!$eg_reason) {
533                 $logger->warn("EDI: Unhandled quantity qty_code '$qty_code' ".
534                     "for li $li_id.  $qty_count items unprocessed");
535                 next;
536             } 
537
538             my ($cancel_count, $fatal) = 
539                 $class->cancel_lids($e, $eg_reason, $qty_count, $lid_count, \@lids);
540
541             last if $fatal;
542
543             $lids_cancelled += $cancel_count;
544
545             # if ALL the items have the same cancel_reason, the LI gets it too
546             $li->cancel_reason($eg_reason->id) if $qty_count == $lid_count;
547                 
548             $li->edit_time('now'); 
549             unless ($e->update_acq_lineitem($li)) {
550                 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
551                 last;
552             }
553         }
554
555         # in case the provider neglected to echo back the order count
556         $order_qty = $lid_count unless defined $order_qty;
557
558         # it may be necessary to change the logic here to look for lineitem
559         # order status / availability status instead of dispatch_qty and 
560         # assume that dispatch_qty simply equals the number of unaccounted-for copies
561         if (defined $dispatch_qty) {
562             # provider is telling us how may copies were delivered
563
564             # number of copies neither cancelled or delivered
565             my $remaining_lids = $order_qty - ($dispatch_qty + $lids_cancelled);
566
567             if ($remaining_lids > 0) {
568
569                 # the vendor did not ship all items and failed to provide cancellation
570                 # quantities for some or all of the items to be cancelled.  When this
571                 # happens, we cancel the remaining un-delivered copies using the
572                 # lineitem order status to determine the cancel reason.
573
574                 my $reason_id;
575                 my $stat;
576
577                 if ($stat = $li_hash->{order_status}) {
578                     $logger->info("EDI: lineitem has order status $stat");
579
580                     if ($stat eq '200') { 
581                         $reason_id = 1007; # not accepted
582
583                     } elsif ($stat eq '400') { 
584                         $reason_id = 1283; # back-order
585                     }
586
587                 } elsif ($stat = $li_hash->{avail_status}) {
588                     $logger->info("EDI: lineitem has availability status $stat");
589
590                     if ($stat eq 'NP') {
591                         # not yet published
592                         # TODO: needs cancellation?
593                     } 
594                 }
595
596                 if ($reason_id) {
597                     my $reason = $e->retrieve_acq_cancel_reason($reason_id);
598
599                     my ($cancel_count, $fatal) = 
600                         $class->cancel_lids($e, $reason, $remaining_lids, $lid_count, \@lids);
601
602                     last if $fatal;
603                     $lids_cancelled += $cancel_count;
604
605                     # All LIDs cancelled with same reason, apply 
606                     # the same cancel reason to the lineitem 
607                     $li->cancel_reason($reason->id) if $remaining_lids == $order_qty;
608                         
609                     $li->edit_time('now'); 
610                     unless ($e->update_acq_lineitem($li)) {
611                         $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
612                         last;
613                     }
614
615                 } else {
616                     $logger->warn("EDI: vendor says we ordered $order_qty and cancelled ". 
617                         "$lids_cancelled, but only shipped $dispatch_qty");
618                 }
619             }
620         }
621
622         # LI and LIDs updated, let's wrap this one up.
623         # this is a no-op if the xact has already been rolled back
624         $e->commit;
625
626         $logger->info("EDI: LI $li_id -- $order_qty LIDs ordered; ". 
627             "$lids_cancelled LIDs cancelled");
628     }
629 }
630
631 sub cancel_lids {
632     my ($class, $e, $reason, $count, $lid_count, $lid_ids) = @_;
633
634     my $cancel_count = 0;
635
636     foreach (1 .. $count) {
637
638         my $lid_id = shift @$lid_ids;
639
640         if (!$lid_id) {
641             $logger->warn("EDI: Used up all $lid_count LIDs. ".
642                 "Ignoring extra status '" . $reason->label . "'");
643             last;
644         }
645
646         my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
647         $lid->cancel_reason($reason->id);
648
649         # item is cancelled.  Remove the fund debit.
650         unless ($U->is_true($reason->keep_debits)) {
651
652             if (my $debit_id = $lid->fund_debit) {
653
654                 $lid->clear_fund_debit;
655                 my $debit = $e->retrieve_acq_fund_debit($debit_id);
656
657                 if ($U->is_true($debit->encumbrance)) {
658                     $logger->info("EDI: deleting debit $debit_id for cancelled LID $lid_id");
659
660                     unless ($e->delete_acq_fund_debit($debit)) {
661                         $logger->error("EDI: unable to update fund_debit " . $e->die_event);
662                         return (0, 1);
663                     }
664                 } else {
665                     # do not delete a paid-for debit
666                     $logger->warn("EDI: cannot delete invoiced debit $debit_id");
667                 }
668             }
669         }
670
671         $e->update_acq_lineitem_detail($lid);
672         $cancel_count++;
673     }
674
675     return ($cancel_count);
676 }
677
678
679 # create_acq_invoice_from_edi() does what it sounds like it does for INVOIC
680 # messages.  For similar operation on ORDRSP messages, see the guts of
681 # process_jedi().
682 # Return boolean success indicator.
683 sub create_acq_invoice_from_edi {
684     my ($class, $invoice, $provider, $message) = @_;
685     # $invoice is O::U::EDIReader hash
686     # $provider is only a pkey
687     # $message is Fieldmapper::acq::edi_message
688
689     my $e = new_editor();
690
691     my $log_prefix = "create_acq_invoice_from_edi(..., <acq.edi_message #" .
692         $message->id . ">): ";
693
694     my $eg_inv = Fieldmapper::acq::invoice->new;
695
696     $eg_inv->provider($provider);
697     $eg_inv->shipper($provider);    # XXX Do we really have a meaningful way to
698                                     # distinguish provider and shipper?
699     $eg_inv->recv_method("EDI");
700
701
702     # some vendors encode the account number as the SAN.
703     # starting with the san value, then the account value, 
704     # treat each as a san, then an acct number until the first success
705     for my $buyer ( ($invoice->{buyer_san}, $invoice->{buyer_acct}) ) {
706         next unless $buyer;
707
708         # some vendors encode the SAN as "$SAN $vendcode"
709         $buyer =~ s/\s.*//g;
710
711         my $addr = $e->search_actor_org_address(
712             {valid => "t", san => $buyer})->[0];
713
714         if ($addr) {
715
716             $eg_inv->receiver($addr->org_unit);
717             last;
718
719         } else {
720
721             my $acct = $e->search_acq_edi_account({vendacct => $buyer})->[0];
722
723             if ($acct) {
724                 $eg_inv->receiver($acct->owner);
725                 last;
726             }
727         }
728     }
729
730     if (!$eg_inv->receiver) {
731         $logger->error($log_prefix . 
732             sprintf("unable to determine buyer (org unit) in invoice; ".
733                 "buyer_san=%s; buyer_acct=%s",
734                 ($invoice->{buyer_san} || ''), 
735                 ($invoice->{buyer_acct} || '')
736             )
737         );
738         return 0;
739     }
740
741     $eg_inv->inv_ident($invoice->{invoice_ident});
742
743     if (!$eg_inv->inv_ident) {
744         $logger->error(
745             $log_prefix . "no invoice ID # in INVOIC message; " . shift
746         );
747         return 0;
748     }
749
750     my @eg_inv_entries;
751
752     $message->purchase_order($invoice->{purchase_order});
753
754     for my $lineitem (@{$invoice->{lineitems}}) {
755         my $li_id = $lineitem->{id};
756
757         if (!$li_id) {
758             $logger->warn($log_prefix . "no lineitem ID");
759             next;
760         }
761
762         my $li = $e->retrieve_acq_lineitem($li_id);
763
764         if (!$li) {
765             $logger->warn($log_prefix . 
766                 "no LI found with ID: $li_id : " . $e->event);
767             return 0;
768         }
769
770         my ($quant) = grep {$_->{code} eq '47'} @{$lineitem->{quantities}};
771         my $quantity = ($quant) ? $quant->{quantity} : 0;
772         
773         if (!$quantity) {
774             $logger->warn($log_prefix . 
775                 "no invoice quantity specified for LI $li_id");
776             next;
777         }
778
779         # NOTE: if needed, we also have $lineitem->{net_unit_price}
780         # and $lineitem->{gross_unit_price}
781         my $lineitem_price = $lineitem->{amount_billed};
782
783         # if the top-level PO value is unset, get it from the first LI
784         $message->purchase_order($li->purchase_order)
785             unless $message->purchase_order;
786
787         my $eg_inv_entry = Fieldmapper::acq::invoice_entry->new;
788         $eg_inv_entry->inv_item_count($quantity);
789
790         # XXX Validate by making sure the LI is on-order and belongs to
791         # the right provider and ordering agency and all that.
792         $eg_inv_entry->lineitem($li_id);
793
794         # XXX Do we actually need to link to PO directly here?
795         $eg_inv_entry->purchase_order($li->purchase_order);
796
797         # This is the total price for all units billed, not per-unit.
798         $eg_inv_entry->cost_billed($lineitem_price);
799
800         push @eg_inv_entries, $eg_inv_entry;
801     }
802
803     my @eg_inv_items;
804
805     my %charge_type_map = (
806         'TX' => ['TAX', 'Tax from electronic invoice'],
807         'CA' => ['PRO', 'Cataloging services'], 
808         'DL' => ['SHP', 'Delivery']
809     );
810
811     for my $charge (@{$invoice->{misc_charges}}) {
812         my $eg_inv_item = Fieldmapper::acq::invoice_item->new;
813
814         my $amount = $charge->{charge_amount};
815
816         if (!$amount) {
817             $logger->warn($log_prefix . "charge with no amount");
818             next;
819         }
820
821         my $map = $charge_type_map{$charge->{charge_type}};
822
823         if (!$map) {
824             $map = [
825                 'PRO',
826                 'Unknown charge type ' .  $charge->{charge_type}
827             ];
828         }
829
830         $eg_inv_item->inv_item_type($$map[0]);
831         $eg_inv_item->note($$map[1]);
832         $eg_inv_item->cost_billed($amount);
833
834         push @eg_inv_items, $eg_inv_item;
835     }
836
837     $logger->info($log_prefix . 
838         sprintf("creating invoice with %d entries and %d items.",
839             scalar(@eg_inv_entries), scalar(@eg_inv_items)));
840
841     $e->xact_begin;
842
843     # save changes to acq.edi_message row
844     if (not $e->update_acq_edi_message($message)) {
845         $logger->error(
846             $log_prefix . "couldn't update edi_message " . $message->id
847         );
848         return 0;
849     }
850
851     # create EG invoice
852     if (not $e->create_acq_invoice($eg_inv)) {
853         $logger->error($log_prefix . "couldn't create invoice: " . $e->event);
854         return 0;
855     }
856
857     # Now we have a pkey for our EG invoice, so set the invoice field on all
858     # our entries according and create those too.
859     my $eg_inv_id = $e->data->id;
860     foreach (@eg_inv_entries) {
861         $_->invoice($eg_inv_id);
862         if (not $e->create_acq_invoice_entry($_)) {
863             $logger->error(
864                 $log_prefix . "couldn't create entry against lineitem " .
865                 $_->lineitem . ": " . $e->event
866             );
867             return 0;
868         }
869     }
870
871     # Create any invoice items (taxes)
872     foreach (@eg_inv_items) {
873         $_->invoice($eg_inv_id);
874         if (not $e->create_acq_invoice_item($_)) {
875             $logger->error(
876                 $log_prefix . "couldn't create inv item: " . $e->event
877             );
878             return 0;
879         }
880     }
881
882     $e->xact_commit;
883     return 1;
884 }
885
886 1;
887