]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Acq/EDI.pm
ORDRSP processing - PO linkage and object refresh
[working/Evergreen.git] / Open-ILS / src / perlmods / 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
19 use Business::EDI;
20
21 use Data::Dumper;
22 our $verbose = 0;
23
24 sub new {
25     my($class, %args) = @_;
26     my $self = bless(\%args, $class);
27     # $self->{args} = {};
28     return $self;
29 }
30
31 # our $reasons = {};   # cache for acq.cancel_reason rows ?
32
33 our $translator;
34
35 sub translator {
36     return $translator ||= OpenILS::Application::Acq::EDI::Translator->new(@_);
37 }
38
39 my %map = (
40     host     => 'remote_host',
41     username => 'remote_user',
42     password => 'remote_password',
43     account  => 'remote_account',
44     # in_dir   => 'remote_path',   # field_map overrides path with in_dir
45     path     => 'remote_path',
46 );
47
48
49 ## Just for debugging stuff:
50 sub add_a_msg {
51     my ($self, $conn) = @_;
52     my $e = new_editor(xact=>1);
53     my $incoming = Fieldmapper::acq::edi_message->new;
54     $incoming->edi("This is content");
55     $incoming->account(1);
56     $incoming->remote_file('in/some_file.edi');
57     $e->create_acq_edi_message($incoming);;
58     $e->commit;
59 }
60 # __PACKAGE__->register_method( method => 'add_a_msg', api_name => 'open-ils.acq.edi.add_a_msg');  # debugging
61
62 __PACKAGE__->register_method(
63         method    => 'retrieve',
64         api_name  => 'open-ils.acq.edi.retrieve',
65         signature => {
66         desc   => 'Fetch incoming message(s) from EDI accounts.  ' .
67                   'Optional arguments to restrict to one vendor and/or a max number of messages.  ' .
68                   'Note that messages are not parsed or processed here, just fetched and translated.',
69         params => [
70             {desc => 'Authentication token',        type => 'string'},
71             {desc => 'Vendor ID (undef for "all")', type => 'number'},
72             {desc => 'Date Inactive Since',         type => 'string'},
73             {desc => 'Max Messages Retrieved',      type => 'number'}
74         ],
75         return => {
76             desc => 'List of new message IDs (empty if none)',
77             type => 'array'
78         }
79     }
80 );
81
82 sub retrieve_core {
83     my ($self, $set, $max, $e, $test) = @_;    # $e is a working editor
84
85     $e   ||= new_editor();
86     $set ||= __PACKAGE__->retrieve_vendors($e);
87
88     my @return = ();
89     my $vcount = 0;
90     foreach my $account (@$set) {
91         my $count = 0;
92         my $server;
93         $logger->info("EDI check for vendor " . ++$vcount . " of " . scalar(@$set) . ": " . $account->host);
94         unless ($server = __PACKAGE__->remote_account($account)) {   # assignment, not comparison
95             $logger->err(sprintf "Failed remote account mapping for %s (%s)", $account->host, $account->id);
96             next;
97         };
98 #       my $rf_starter = './';  # default to current dir
99         if ($account->in_dir) { 
100             if ($account->in_dir =~ /\*+.*\//) {
101                 $logger->err("EDI in_dir has a slash after an asterisk in value: '" . $account->in_dir . "'.  Skipping account with indeterminate target dir!");
102                 next;
103             }
104 #           $rf_starter = $account->in_dir;
105 #           $rf_starter =~ s/((\/)?[^\/]*)\*+[^\/]*$//;  # kill up to the first (possible) slash before the asterisk: keep the preceeding static dir
106 #           $rf_starter .= '/' if $rf_starter or $2;   # recap the dir, or replace leading "/" if there was one (but don't add if empty)
107         }
108         my @files    = ($server->ls({remote_file => ($account->in_dir || './')}));
109         my @ok_files = grep {$_ !~ /\/\.?\.$/ and $_ ne '0'} @files;
110         $logger->info(sprintf "%s of %s files at %s/%s", scalar(@ok_files), scalar(@files), $account->host, $account->in_dir);   
111         # $server->remote_path(undef);
112         foreach my $remote_file (@ok_files) {
113             # my $remote_file = $rf_starter . $_;
114             my $description = sprintf "%s/%s", $account->host, $remote_file;
115             
116             # deduplicate vs. acct/filenames already in DB
117             my $hits = $e->search_acq_edi_message([
118                 {
119                     account     => $account->id,
120                     remote_file => $remote_file,
121                     status      => {'in' => [qw/ processed /]},     # if it never got processed, go ahead and get the new one (try again)
122                     # create_time => 'NOW() - 60 DAYS',     # if we wanted to allow filenames to be reused after a certain time
123                     # ideally we would also use the date from FTP, but that info isn't available via RemoteAccount
124                 }
125                 # { flesh => 1, flesh_fields => {...}, }
126             ]);
127             if (scalar(@$hits)) {
128                 $logger->debug("EDI: $remote_file already retrieved.  Skipping");
129                 warn "EDI: $remote_file already retrieved.  Skipping";
130                 next;
131             }
132
133             ++$count;
134             $max and $count > $max and last;
135             $logger->info(sprintf "%s of %s targets: %s", $count, scalar(@ok_files), $description);
136             print sprintf "%s of %s targets: %s\n", $count, scalar(@ok_files), $description;
137             if ($test) {
138                 push @return, "test_$count";
139                 next;
140             }
141             my $content;
142             my $io = IO::Scalar->new(\$content);
143             unless ( $server->get({remote_file => $remote_file, local_file => $io}) ) {
144                 $logger->error("(S)FTP get($description) failed");
145                 next;
146             }
147             my $incoming = __PACKAGE__->process_retrieval($content, $remote_file, $server, $account->id, $e);
148 #           $server->delete(remote_file => $_);   # delete remote copies of saved message
149             push @return, $incoming->id;
150         }
151     }
152     return \@return;
153 }
154
155 # my $in = OpenILS::Application::Acq::EDI->process_retrieval($file_content, $remote_filename, $server, $account_id, $editor);
156
157 sub process_retrieval {
158     my $incoming = Fieldmapper::acq::edi_message->new;
159     my ($class, $content, $remote, $server, $account_or_id, $e) = @_;
160     $content or return;
161     $e ||= new_editor;
162
163     my $account = __PACKAGE__->record_activity( $account_or_id, $e );
164
165     my $z;  # must predeclare
166     $z = ( $content =~ s/('UNH\+\d+\+ORDRSP:)0(:96A:UN')/$1D$2/g )
167         and $logger->warn("Patching bogus spec reference ORDRSP:0:96A:UN => ORDRSP:D:96A:UN ($z times)");  # Hack/fix some faulty "0" in (B&T) data
168
169     $incoming->remote_file($remote);
170     $incoming->account($account->id);
171     $incoming->edi($content);
172     $incoming->message_type(($content =~ /'UNH\+\d+\+(\S{6}):/) ? $1 : 'ORDRSP');   # cheap sniffing, ORDRSP fallback
173     __PACKAGE__->attempt_translation($incoming);
174     $e->xact_begin;
175     $e->create_acq_edi_message($incoming);
176     $e->xact_commit;
177     # refresh: send process_jedi the updated row
178     my $res = __PACKAGE__->process_jedi($e->retrieve_acq_edi_message($incoming->id), $server, $account, $e);
179     my $outgoing = $e->retrieve_acq_edi_message($incoming->id);  # refresh again!
180     $outgoing->status($res ? 'processed' : 'proc_error');
181     if ($res) {
182         $e->xact_begin;
183         $e->update_acq_edi_message($outgoing);
184         $e->xact_commit;
185     }
186     return $outgoing;
187 }
188
189 # ->send_core
190 # $account     is a Fieldmapper object for acq.edi_account row
191 # $messageset  is an arrayref with acq.edi_message.id values
192 # $e           is optional editor object
193 sub send_core {
194     my ($class, $account, $message_ids, $e) = @_;    # $e is a working editor
195
196     ($account and scalar @$message_ids) or return;
197     $e ||= new_editor();
198
199     my @messageset = map {$e->retrieve_acq_edi_message($_)} @$message_ids;
200     my $m_count = scalar(@messageset);
201     (scalar(@$message_ids) == $m_count) or
202         $logger->warn(scalar(@$message_ids) - $m_count . " bad IDs passed to send_core (ignored)");
203
204     my $log_str = sprintf "EDI send to edi_account %s (%s)", $account->id, $account->host;
205     $logger->info("$log_str: $m_count message(s)");
206     $m_count or return;
207
208     my $server;
209     my $server_error;
210     unless ($server = __PACKAGE__->remote_account($account, 1)) {   # assignment, not comparison
211         $logger->error("Failed remote account connection for $log_str");
212         $server_error = 1;
213     };
214     foreach (@messageset) {
215         $_ or next;     # we already warned about bum ids
216         my ($res, $error);
217         if ($server_error) {
218             $error = "Server error: Failed remote account connection for $log_str"; # already told $logger, this is to update object below
219         } elsif (! $_->edi) {
220             $logger->error("Message (id " . $_->id. ") for $log_str has no EDI content");
221             $error = "EDI empty!";
222         } elsif ($res = $server->put({remote_path => $account->path, content => $_->edi, single_ext => 1})) {
223             #  This is the successful case!
224             $_->remote_file($res);
225             $_->status('complete');
226             $_->process_time('NOW');    # For outbound files, sending is the end of processing on the EG side.
227             $logger->info("Sent message (id " . $_->id. ") via $log_str");
228         } else {
229             $logger->error("(S)FTP put to $log_str FAILED: " . ($server->error || 'UNKOWNN'));
230             $error = "put FAILED: " . ($server->error || 'UNKOWNN');
231         }
232         if ($error) {
233             $_->error($error);
234             $_->error_time('NOW');
235         }
236         $logger->info("Calling update_acq_edi_message");
237         $e->xact_begin;
238         unless ($e->update_acq_edi_message($_)) {
239              $logger->error("EDI send_core update_acq_edi_message failed for message object: " . Dumper($_));
240              OpenILS::Application::Acq::EDI::Translator->debug_file(Dumper($_              ), '/tmp/update_acq_edi_message.FAIL');
241              OpenILS::Application::Acq::EDI::Translator->debug_file(Dumper($_->to_bare_hash), '/tmp/update_acq_edi_message.FAIL.to_bare_hash');
242         }
243         # There's always an update, even if we failed.
244         $e->xact_commit;
245         __PACKAGE__->record_activity($account, $e);  # There's always an update, even if we failed.
246     }
247     return \@messageset;
248 }
249
250 #  attempt_translation does not touch the DB, just the object.  
251 sub attempt_translation {
252     my ($class, $edi_message, $to_edi) = @_;
253     my $tran  = translator();
254     my $ret   = $to_edi ? $tran->json2edi($edi_message->jedi) : $tran->edi2json($edi_message->edi);
255 #   $logger->error("json: " . Dumper($json)); # debugging
256     if (not $ret or (! ref($ret)) or $ret->is_fault) {      # RPC::XML::fault on failure
257         $edi_message->status('trans_error');
258         $edi_message->error_time('NOW');
259         my $pre = "EDI Translator " . ($to_edi ? 'json2edi' : 'edi2json') . " failed";
260         my $message = ref($ret) ? 
261                       ("$pre, Error " . $ret->code . ": " . __PACKAGE__->nice_string($ret->string)) :
262                       ("$pre: "                           . __PACKAGE__->nice_string($ret)        ) ;
263         $edi_message->error($message);
264         $logger->error(  $message);
265         return;
266     }
267     $edi_message->status('translated');
268     $edi_message->translate_time('NOW');
269     if ($to_edi) {
270         $edi_message->edi($ret->value);    # translator returns an object
271     } else {
272         $edi_message->jedi($ret->value);   # translator returns an object
273     }
274     return $edi_message;
275 }
276
277 sub retrieve_vendors {
278     my ($self, $e, $vendor_id, $last_activity) = @_;    # $e is a working editor
279
280     $e ||= new_editor();
281
282     my $criteria = {'+acqpro' => {active => 't'}};
283     $criteria->{'+acqpro'}->{id} = $vendor_id if $vendor_id;
284     return $e->search_acq_edi_account([
285         $criteria, {
286             'join' => 'acqpro',
287             flesh => 1,
288             flesh_fields => {
289                 acqedi => ['provider']
290             }
291         }
292     ]);
293 #   {"id":{"!=":null},"+acqpro":{"active":"t"}}, {"join":"acqpro", "flesh_fields":{"acqedi":["provider"]},"flesh":1}
294 }
295
296 # This is the SRF-exposed call, so it does checkauth
297
298 sub retrieve {
299     my ($self, $conn, $auth, $vendor_id, $last_activity, $max) = @_;
300
301     my $e = new_editor(authtoken=>$auth);
302     unless ($e and $e->checkauth()) {
303         $logger->warn("checkauth failed for authtoken '$auth'");
304         return ();
305     }
306     # return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);  # add permission here ?
307
308     my $set = __PACKAGE__->retrieve_vendors($e, $vendor_id, $last_activity) or return $e->die_event;
309     return __PACKAGE__->retrieve_core($e, $set, $max);
310 }
311
312
313 # field_map takes the hashref of vendor data with fields from acq.edi_account and 
314 # maps them to the argument style needed for RemoteAccount.  It also extrapolates
315 # data from the remote_host string for type and port, when available.
316
317 sub field_map {
318     my $self   = shift;
319     my $vendor = shift or return;
320     my $no_override = @_ ? shift : 0;
321     my %args = ();
322     $verbose and $logger->warn("vendor: " . Dumper($vendor));
323     foreach (keys %map) {
324         $args{$map{$_}} = $vendor->$_ if defined $vendor->$_;
325     }
326     unless ($no_override) {
327         $args{remote_path} = $vendor->in_dir;    # override "path" with "in_dir"
328     }
329     my $host = $args{remote_host} || '';
330     ($host =~ s/^(S?FTP)://i    and $args{type} = uc($1)) or
331     ($host =~ s/^(SSH|SCP)://i  and $args{type} = 'SCP' ) ;
332      $host =~ s/:(\d+)$//       and $args{port} = $1;
333     ($args{remote_host} = $host) =~ s#/+##;
334     $verbose and $logger->warn("field_map: " . Dumper(\%args));
335     return %args;
336 }
337
338
339 # The point of remote_account is to get the RemoteAccount object with args from the DB
340
341 sub remote_account {
342     my ($self, $vendor, $outbound, $e) = @_;
343
344     unless (ref($vendor)) {     # It's not a hashref/object.
345         $vendor or return;      # If in fact it's nothing: abort!
346                                 # else it's a vendor_id string, so get the full vendor data
347         $e ||= new_editor();
348         my $set_of_one = $self->retrieve_vendors($e, $vendor) or return;
349         $vendor = shift @$set_of_one;
350     }
351
352     return OpenILS::Utils::RemoteAccount->new(
353         $self->field_map($vendor, $outbound)
354     );
355 }
356
357 # takes account ID or account Fieldmapper object
358
359 sub record_activity {
360     my ($class, $account_or_id, $e) = @_;
361     $account_or_id or return;
362     $e ||= new_editor();
363     my $account = ref($account_or_id) ? $account_or_id : $e->retrieve_acq_edi_account($account_or_id);
364     $logger->info("EDI record_activity calling update_acq_edi_account");
365     $account->last_activity('NOW') or return;
366     $e->xact_begin;
367     $e->update_acq_edi_account($account) or $logger->warn("EDI: in record_activity, update_acq_edi_account FAILED");
368     $e->xact_commit;
369     return $account;
370 }
371
372 sub nice_string {
373     my $class = shift;
374     my $string = shift or return '';
375     chomp($string);
376     my $head   = @_ ? shift : 100;
377     my $tail   = @_ ? shift :  25;
378     (length($string) < $head + $tail) and return $string;
379     my $h = substr($string,0,$head);
380     my $t = substr($string, -1*$tail);
381     $h =~s/\s*$//o;
382     $t =~s/\s*$//o;
383     return "$h ... $t";
384     # return substr($string,0,$head) . "... " . substr($string, -1*$tail);
385 }
386
387 sub jedi2perl {
388     my ($class, $jedi) = @_;
389     $jedi or return;
390     my $msg = OpenSRF::Utils::JSON->JSON2perl( $jedi );
391     open (FOO, ">>/tmp/JSON2perl_dump.txt");
392     print FOO Dumper($msg), "\n\n";
393     close FOO;
394     $logger->warn("Dumped JSON2perl to /tmp/JSON2perl_dump.txt");
395     return $msg;
396 }
397
398 our @datecodes = (35, 359, 17, 191, 69, 76, 75, 79, 85, 74, 84, 223);
399 our @noop_6063 = (21);
400
401 # ->process_jedi($message, $server, $remote, $e)
402 # $message is an edi_message object
403 #
404 sub process_jedi {
405     my ($class, $message, $server, $remote, $e) = @_;
406     $message or return;
407     $server ||= {};  # context
408     $remote ||= {};  # context
409     $e ||= new_editor;
410     my $jedi;
411     unless (ref($message) and $jedi = $message->jedi) {     # assignment, not comparison
412         $logger->warn("EDI process_jedi missing required argument (edi_message object with jedi)!");
413         return;
414     }
415     my $perl  = __PACKAGE__->jedi2perl($jedi);
416     my $error = '';
417     if (ref($message) and not $perl) {
418         $error = ($message->error || '') . " JSON2perl (jedi2perl) FAILED to convert jedi";
419     }
420     elsif (! $perl->{body}) {
421         $error = "EDI interchange body not found!";
422     } 
423     elsif (! $perl->{body}->[0]) {
424         $error = "EDI interchange body not a populated arrayref!";
425     }
426     if ($error) {
427         $logger->warn($error);
428         $message->error($error);
429         $message->error_time('NOW');
430         $e->xact_begin;
431         $e->update_acq_edi_message($message) or $logger->warn("EDI update_acq_edi_message failed! $!");
432         $e->xact_commit;
433         return;
434     }
435
436 # Crazy data structure.  Most of the arrays will be 1 element... we think.
437 # JEDI looks like:
438 # {'body' => [{'ORDERS' => [['UNH',{'0062' => '4635','S009' => {'0057' => 'EAN008','0051' => 'UN','0052' => 'D','0065' => 'ORDERS', ...
439
440 # So you might access it like:
441 #   $obj->{body}->[0]->{ORDERS}->[0]->[0] eq 'UNH'
442
443     $logger->info("EDI interchange body has " . scalar(@{$perl->{body}}) . " message(s)");
444     my @ok_msg_codes = qw/ORDRSP OSTRPT/;
445     my @messages;
446     my $i = 0;
447     foreach my $part (@{$perl->{body}}) {
448         $i++;
449         unless (ref $part and scalar keys %$part) {
450             $logger->warn("EDI interchange message $i lacks structure.  Skipping it.");
451             next;
452         }
453         foreach my $key (keys %$part) {
454             if (! grep {$_ eq $key} @ok_msg_codes) {     # We only do one type for now.  TODO: other types here
455                 $logger->warn("EDI interchange $i contains unhandled '$key' message.  Ignoring it.");
456                 next;
457             }
458             my $msg = __PACKAGE__->message_object($part->{$key}) or next;
459             push @messages, $msg;
460
461             my $bgm = $msg->xpath('BGM') or $logger->warn("EDI No BGM segment found?!");
462             my $tag4343 = $msg->xpath('BGM/4343');
463             my $tag1225 = $msg->xpath('BGM/1225');
464             if (ref $tag4343) {
465                 $logger->info(sprintf "EDI $key BGM/4343 Response Type: %s - %s", $tag4343->value, $tag4343->label)
466             } else {
467                 $logger->warn("EDI $key BGM/4343 Response Type Code unrecognized"); # next; #?
468             }
469             if (ref $tag1225) {
470                 $logger->info(sprintf "EDI $key BGM/1225 Message Function: %s - %s", $tag1225->value, $tag1225->label);
471             } else {
472                 $logger->warn("EDI $key BGM/1225 Message Function Code unrecognized"); # next; #?
473             }
474
475             # TODO: currency check, just to be paranoid
476             # *should* be unnecessary (vendor should reply in currency we send in ORDERS)
477             # That begs a policy question: how to handle mismatch?  convert (bad accuracy), reject, or ignore?  I say ignore.
478
479             # ALL those codes below are basically some form of (lastest) delivery date/time
480             # see, e.g.: http://www.stylusstudio.com/edifact/D04B/2005.htm
481             # The order is the order of definitiveness (first match wins)
482             # Note: if/when we do serials via EDI, dates (and ranges/periods) will need massive special handling
483             my @dates;
484             my $ddate;
485
486             foreach my $date ($msg->xpath('delivery_schedule')) {
487                 my $val_2005 = $date->xpath_value('DTM/2005') or next;
488                 (grep {$val_2005 eq $_} @datecodes) or next; # no match means some other kind of date we don't care about
489                 push @dates, $date;
490             }
491             if (@dates) {
492                 DATECODE: foreach my $dcode (@datecodes) {   # now cycle back through hits in order of dcode definitiveness
493                     foreach my $date (@dates) {
494                         $date->xpath_value('DTM/2005') == $dcode or next;
495                         $ddate = $date->xpath_value('DTM/2380') and last DATECODE;
496                         # TODO: conversion based on format specified in DTM/2379 (best encapsulated in Business::EDI)
497                     }
498                 }
499             }
500             foreach my $detail ($msg->part('line_detail')) {
501                 my $eg_line = __PACKAGE__->eg_li($detail, $remote, $server->{remote_host}, $e) or next;
502                 my $li_date = $detail->xpath_value('DTM/2380') || $ddate;
503                 my $price   = $detail->xpath_value('line_price/PRI/5118') || '';
504                 $eg_line->expected_recv_time($li_date) if $li_date;
505                 $eg_line->estimated_unit_price($price) if $price;
506                 if (not $message->purchase_order) {                     # first good lineitem sets the message PO link
507                     $message->purchase_order($eg_line->purchase_order); # EG $message object NOT Business::EDI $msg object
508                     $e->xact_begin;
509                     $e->update_acq_edi_message($message) or $logger->warn("EDI update_acq_edi_message (for PO number) failed! $!");
510                     $e->xact_commit;
511                 }
512                 # $e->search_acq_edi_account([]);
513                 my $touches = 0;
514                 my $eg_lids = $e->search_acq_lineitem_detail({lineitem => $eg_line->id}); # should be the same as $eg_line->lineitem_details
515                 my $lidcount = scalar(@$eg_lids);
516                 $lidcount == $eg_line->item_count or $logger->warn(
517                     sprintf "EDI: LI %s itemcount (%d) mismatch, %d LIDs found", $eg_line->id, $eg_line->item_count, $lidcount
518                 );
519                 foreach my $qty ($detail->part('all_QTY')) {
520                     my $ubound   = $qty->xpath_value('6060') or next;   # nothing to do if qty is 0
521                     my $val_6063 = $qty->xpath_value('6063');
522                     $ubound > 0 or next; # don't be crazy!
523                     if (! $val_6063) {
524                         $logger->warn("EDI: Response for LI " . $eg_line->id . " specifies quantity $ubound with no 6063 code! Contact vendor to resolve.");
525                         next;
526                     }
527                     
528                     my $eg_reason = $e->retrieve_acq_cancel_reason(1200 + $val_6063);  # DB populated w/ 6063 keys in 1200's
529                     if (! $eg_reason) {
530                         $logger->warn("EDI: Unhandled quantity code '$val_6063' (LI " . $eg_line->id . ") $ubound items unprocessed");
531                         next;
532                     } elsif (grep {$val_6063 == $_} @noop_6063) {      # an FYI like "ordered quantity"
533                         $ubound eq $lidcount
534                             or $logger->warn("EDI: LI " . $eg_line->id . " -- Vendor says we ordered $ubound, but we have $lidcount LIDs!)");
535                         next;
536                     }
537                     # elsif ($val_6063 == 83) { # backorder
538                    #} elsif ($val_6063 == 85) { # cancel
539                    #} elsif ($val_6063 == 12 or $val_6063 == 57 or $val_6063 == 84 or $val_6063 == 118) {
540                             # despatched, in transit, urgent delivery, or quantity manifested
541                    #}
542                     if ($touches >= $lidcount) {
543                         $logger->warn("EDI: LI "  . $eg_line->id . ", We already updated $touches of $lidcount LIDS, " .
544                                       "but message wants QTY $ubound more set to " . $eg_reason->label . ".  Ignoring!");
545                         next;
546                     }
547                     $e->xact_begin;
548                     foreach (1 .. $ubound) {
549                         my $eg_lid = shift @$eg_lids or $logger->warn("EDI: Used up all $lidcount LIDs!  Ignoring extra status " . $eg_reason->label);
550                         $eg_lid or next;
551                         $logger->debug(sprintf "Updating LID %s to %s", $eg_lid->id, $eg_reason->label);
552                         $eg_lid->cancel_reason($eg_reason->id);
553                         $e->update_acq_lineitem_detail($eg_lid);
554                         $touches++;
555                     }
556                     $e->xact_commit;
557                     if ($ubound == $eg_line->item_count) {
558                         $eg_line->cancel_reason($eg_reason->id);    # if ALL the items have the same cancel_reason, the PO gets it too
559                     }
560                 }
561                 $eg_line->edit_time('NOW'); # TODO: have this field automatically updated via ON UPDATE trigger.  
562                 $e->xact_begin;
563                 $e->update_acq_lineitem($eg_line) or $logger->warn("EDI: update_acq_lineitem FAILED");
564                 $e->xact_commit;
565                 # print STDERR "Lineitem update: ", Dumper($eg_line);
566             }
567         }
568     }
569     return \@messages;
570 }
571
572 # returns message object if processing should continue
573 # returns false/undef value if processing should abort
574
575 sub message_object {
576     my $class = shift;
577     my $body  = shift or return;
578     my $key   = shift if @_;
579     my $keystring = $key || 'UNSPECIFIED';
580
581     my $msg = Business::EDI::Message->new($body);
582     unless ($msg) {
583         $logger->error("EDI interchange message: $keystring body failed Business::EDI constructor. Skipping it.");
584         return;
585     }
586     $key = $msg->code if ! $key;  # Now we set the key for reference if it wasn't specified
587     my $val_0065 = $msg->xpath_value('UNH/S009/0065') || '';
588     unless ($val_0065 eq $key) {
589         $logger->error("EDI $key UNH/S009/0065 ('$val_0065') conflicts w/ message type $key.  Aborting");
590         return;
591     }
592     my $val_0051 = $msg->xpath_value('UNH/S009/0051') || '';
593     unless ($val_0051 eq 'UN') {
594         $logger->warn("EDI $key UNH/S009/0051 designates '$val_0051', not 'UN' as controlling agency.  Attempting to process anyway");
595     }
596     my $val_0054 = $msg->xpath_value('UNH/S009/0054') || '';
597     if ($val_0054) {
598         $logger->info("EDI $key UNH/S009/0054 uses Spec revision version '$val_0054'");
599         # Possible Spec Version limitation
600         # my $yy = $tag_0054 ? substr($val_0054,0,2) : '';
601         # unless ($yy eq '00' or $yy > 94 ...) {
602         #     $logger->warn("EDI $key UNH/S009/0051 Spec revision version '$val_0054' not supported");
603         # }
604     } else {
605         $logger->warn("EDI $key UNH/S009/0054 does not reference a known Spec revision version");
606     }
607     return $msg;
608 }
609
610 =head2 ->eg_li($lineitem_object, [$remote, $server_log_string, $editor])
611
612 my $line_item = OpenILS::Application::Acq::EDI->eg_li($edi_line, $remote, "test_server_01", $e);
613
614  $remote is a acq.edi_account Fieldmapper object.
615  $server_log_string is an arbitrary string use to identify the remote host in potential log messages.
616
617 Updates:
618  acq.lineitem.estimated_unit_price, 
619  acq.lineitem.state (dependent on mapping codes), 
620  acq.lineitem.expected_recv_time, 
621  acq.lineitem.edit_time (consequently)
622
623 =cut
624
625 sub eg_li {
626     my ($class, $line, $server, $server_log_string, $e) = @_;
627     $line or return;
628     $e ||= new_editor();
629
630     my $id;
631     # my $rff      = $line->part('line_reference/RFF') or $logger->warn("EDI ORDRSP line_detail/RFF missing!");
632     my $val_1153 = $line->xpath_value('line_reference/RFF/1153') || '';
633     my $val_1154 = $line->xpath_value('line_reference/RFF/1154') || '';
634     my $val_1082 = $line->xpath_value('LIN/1082') || '';
635
636     my @po_nums;
637
638     $val_1154 =~ s#^(.*)\/##;   # Many sources send the ID as 'order_ID/LI_ID'
639     $1 and push @po_nums, $1;
640     $val_1082 =~ s#^(.*)\/##;   # Many sources send the ID as 'order_ID/LI_ID'
641     $1 and push @po_nums, $1;
642
643     # TODO: possible check of po_nums
644     # now do a lot of checking
645
646     if ($val_1153 eq 'LI') {
647         $id = $val_1154 or $logger->warn("EDI ORDRSP RFF/1154 reference to LI empty.  Attempting failover to LIN/1082");
648     } else {
649         $logger->warn("EDI ORDRSP RFF/1153 unexpected value ('$val_1153', not 'LI').  Attempting failover to LIN/1082");
650     }
651
652     if ($id and $val_1082 and $val_1082 ne $id) {
653         $logger->warn("EDI ORDRSP LIN/1082 Line Item ID mismatch ($id vs. $val_1082): cannot target update");
654         return;
655     }
656     $id ||= $val_1082 || '';
657     print STDERR "EDI retrieve/update lineitem $id\n";
658
659     my $li = OpenILS::Application::Acq::Lineitem::retrieve_lineitem_impl($e, $id, {
660         flesh_li_details => 1,
661     }, 1); # Could send more {options}.  The 1 is for no_auth.
662
663     if (! $li or ref($li) ne 'Fieldmapper::acq::lineitem') {
664         $logger->error("EDI failed to retrieve lineitem by id '$id' for server $server_log_string");
665         return;
666     }
667     unless ((! $server) or (! $server->provider)) {     # but here we want $server to be acq.edi_account instead of RemoteAccount
668         if ($server->provider != $li->provider) {
669             # links go both ways: acq.provider.edi_default and acq.edi_account.provider
670             $logger->info("EDI acct provider (" . $server->provider. ") doesn't match lineitem provider("
671                             . $li->provider . ").  Checking acq.provider.edi_default...");
672             my $provider = $e->retrieve_acq_provider($li->provider);
673             if ($provider->edi_default != $server->id) {
674                 $logger->error(sprintf "EDI provider/acct %s/%s (%s) is blocked from updating lineitem $id belonging to provider/edi_default %s/%s",
675                                 $server->provider, $server->id, $server->label, $li->provider, $provider->edi_default);
676                 return;
677             }
678         }
679     }
680     
681     my @lin_1229 = $line->xpath('LIN/1229') or $logger->warn("EDI LIN/1229 Action Code missing!");
682     my $key = $lin_1229[0] or return;
683
684     my $eg_reason = $e->retrieve_acq_cancel_reason(1000 + $key->value);  # DB populated w/ spec keys in 1000's
685     $eg_reason or $logger->warn(sprintf "EDI LIN/1229 Action Code '%s' (%s) not recognized in acq.cancel_reason", $key->value, $key->label);
686     $eg_reason or return;
687
688     $li->cancel_reason($eg_reason->id);
689     unless ($eg_reason->keep_debits) {
690         $logger->warn("EDI LIN/1229 Action Code '%s' (%s) has keep_debits=0", $key->value, $key->label);
691     }
692
693     my @prices = $line->xpath_value("line_price/PRI/5118");
694     $li->estimated_unit_price($prices[0]) if @prices;
695
696     return $li;
697 }
698
699 # caching not needed for now (edi_fetcher is asynchronous)
700 # sub get_reason {
701 #     my ($class, $key, $e) = @_;
702 #     $reasons->{$key} and return $reasons->{$key};
703 #     $e ||= new_editor();
704 #     $reasons->{$key} = $e->retrieve_acq_cancel_reason($key);
705 #     return $reasons->{$key};
706 # }
707
708 1;
709
710 __END__
711
712 Example JSON data.
713
714 Note the pseudo-hash 2-element arrays.  
715
716 [
717   'SG26',
718   [
719     [
720       'LIN',
721       {
722         '1229' => '5',
723         '1082' => 1,
724         'C212' => {
725           '7140' => '9780446360272',
726           '7143' => 'EN'
727         }
728       }
729     ],
730     [
731       'IMD',
732       {
733         '7081' => 'BST',
734         '7077' => 'F',
735         'C273' => {
736           '7008' => [
737             'NOT APPLIC WEBSTERS NEW WORLD THESA'
738           ]
739         }
740       }
741     ],
742     [
743       'QTY',
744       {
745         'C186' => {
746           '6063' => '21',
747           '6060' => 10
748         }
749       }
750     ],
751     [
752       'QTY',
753       {
754         'C186' => {
755           '6063' => '12',
756           '6060' => 10
757         }
758       }
759     ],
760     [
761       'QTY',
762       {
763         'C186' => {
764           '6063' => '85',
765           '6060' => 0
766         }
767       }
768     ],
769     [
770       'FTX',
771       {
772         '4451' => 'LIN',
773         'C107' => {
774           '4441' => '01',
775           '3055' => '28',
776           '1131' => '8B'
777         }
778       }
779     ],
780     [
781       'SG30',
782       [
783         [
784           'PRI',
785           {
786             'C509' => {
787               '5118' => '4.5',
788               '5387' => 'SRP',
789               '5125' => 'AAB'
790             }
791           }
792         ]
793       ]
794     ],
795     [
796       'SG31',
797       [
798         [
799           'RFF',
800           {
801             'C506' => {
802               '1154' => '8/1',
803               '1153' => 'LI'
804             }
805           }
806         ]
807       ]
808     ]
809   ]
810 ],
811