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