1 package OpenILS::Application::Acq::EDI;
2 use base qw/OpenILS::Application/;
4 use strict; use warnings;
8 use OpenSRF::AppSession;
9 use OpenSRF::EX qw/:try/;
10 use OpenSRF::Utils::Logger qw(:logger);
11 use OpenSRF::Utils::JSON;
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;
25 my($class, %args) = @_;
26 my $self = bless(\%args, $class);
31 # our $reasons = {}; # cache for acq.cancel_reason rows ?
36 return $translator ||= OpenILS::Application::Acq::EDI::Translator->new(@_);
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',
49 ## Just for debugging stuff:
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);;
60 # __PACKAGE__->register_method( method => 'add_a_msg', api_name => 'open-ils.acq.edi.add_a_msg'); # debugging
62 __PACKAGE__->register_method(
64 api_name => 'open-ils.acq.edi.retrieve',
67 desc => 'Fetch incoming message(s) from EDI accounts. ' .
68 'Optional arguments to restrict to one vendor and/or a max number of messages. ' .
69 'Note that messages are not parsed or processed here, just fetched and translated.',
71 {desc => 'Authentication token', type => 'string'},
72 {desc => 'Vendor ID (undef for "all")', type => 'number'},
73 {desc => 'Date Inactive Since', type => 'string'},
74 {desc => 'Max Messages Retrieved', type => 'number'}
77 desc => 'List of new message IDs (empty if none)',
84 my ($self, $set, $max, $e, $test) = @_; # $e is a working editor
87 $set ||= __PACKAGE__->retrieve_vendors($e);
91 foreach my $account (@$set) {
94 $logger->info("EDI check for vendor " . ++$vcount . " of " . scalar(@$set) . ": " . $account->host);
95 unless ($server = __PACKAGE__->remote_account($account)) { # assignment, not comparison
96 $logger->err(sprintf "Failed remote account mapping for %s (%s)", $account->host, $account->id);
99 # my $rf_starter = './'; # default to current dir
100 if ($account->in_dir) {
101 if ($account->in_dir =~ /\*+.*\//) {
102 $logger->err("EDI in_dir has a slash after an asterisk in value: '" . $account->in_dir . "'. Skipping account with indeterminate target dir!");
105 # $rf_starter = $account->in_dir;
106 # $rf_starter =~ s/((\/)?[^\/]*)\*+[^\/]*$//; # kill up to the first (possible) slash before the asterisk: keep the preceeding static dir
107 # $rf_starter .= '/' if $rf_starter or $2; # recap the dir, or replace leading "/" if there was one (but don't add if empty)
109 my @files = ($server->ls({remote_file => ($account->in_dir || './')}));
110 my @ok_files = grep {$_ !~ /\/\.?\.$/ and $_ ne '0'} @files;
111 $logger->info(sprintf "%s of %s files at %s/%s", scalar(@ok_files), scalar(@files), $account->host, $account->in_dir);
112 # $server->remote_path(undef);
113 foreach my $remote_file (@ok_files) {
114 # my $remote_file = $rf_starter . $_;
115 my $description = sprintf "%s/%s", $account->host, $remote_file;
117 # deduplicate vs. acct/filenames already in DB
118 my $hits = $e->search_acq_edi_message([
120 account => $account->id,
121 remote_file => $remote_file,
122 status => {'in' => [qw/ processed /]}, # if it never got processed, go ahead and get the new one (try again)
123 # create_time => 'NOW() - 60 DAYS', # if we wanted to allow filenames to be reused after a certain time
124 # ideally we would also use the date from FTP, but that info isn't available via RemoteAccount
126 # { flesh => 1, flesh_fields => {...}, }
128 if (scalar(@$hits)) {
129 $logger->debug("EDI: $remote_file already retrieved. Skipping");
130 warn "EDI: $remote_file already retrieved. Skipping";
135 $max and $count > $max and last;
136 $logger->info(sprintf "%s of %s targets: %s", $count, scalar(@ok_files), $description);
137 print sprintf "%s of %s targets: %s\n", $count, scalar(@ok_files), $description;
139 push @return, "test_$count";
143 my $io = IO::Scalar->new(\$content);
144 unless ( $server->get({remote_file => $remote_file, local_file => $io}) ) {
145 $logger->error("(S)FTP get($description) failed");
148 my $incoming = __PACKAGE__->process_retrieval($content, $remote_file, $server, $account->id, $e);
149 # $server->delete(remote_file => $_); # delete remote copies of saved message
150 push @return, $incoming->id;
156 # my $in = OpenILS::Application::Acq::EDI->process_retrieval($file_content, $remote_filename, $server, $account_id, $editor);
158 sub process_retrieval {
159 my $incoming = Fieldmapper::acq::edi_message->new;
160 my ($class, $content, $remote, $server, $account_or_id, $e) = @_;
164 my $account = __PACKAGE__->record_activity( $account_or_id, $e );
166 my $z; # must predeclare
167 $z = ( $content =~ s/('UNH\+\d+\+ORDRSP:)0(:96A:UN')/$1D$2/g )
168 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
170 $incoming->remote_file($remote);
171 $incoming->account($account->id);
172 $incoming->edi($content);
173 $incoming->message_type(($content =~ /'UNH\+\d+\+(\S{6}):/) ? $1 : 'ORDRSP'); # cheap sniffing, ORDRSP fallback
174 __PACKAGE__->attempt_translation($incoming);
176 $e->create_acq_edi_message($incoming);
178 # refresh: send process_jedi the updated row
180 my $outgoing = $e->retrieve_acq_edi_message($incoming->id); # refresh again!
182 my $res = __PACKAGE__->process_jedi($outgoing, $server, $account, $e);
184 $outgoing = $e->retrieve_acq_edi_message($incoming->id); # refresh again!
186 $outgoing->status($res ? 'processed' : 'proc_error');
189 $e->update_acq_edi_message($outgoing);
196 # $account is a Fieldmapper object for acq.edi_account row
197 # $messageset is an arrayref with acq.edi_message.id values
198 # $e is optional editor object
200 my ($class, $account, $message_ids, $e) = @_; # $e is a working editor
202 ($account and scalar @$message_ids) or return;
206 my @messageset = map {$e->retrieve_acq_edi_message($_)} @$message_ids;
208 my $m_count = scalar(@messageset);
209 (scalar(@$message_ids) == $m_count) or
210 $logger->warn(scalar(@$message_ids) - $m_count . " bad IDs passed to send_core (ignored)");
212 my $log_str = sprintf "EDI send to edi_account %s (%s)", $account->id, $account->host;
213 $logger->info("$log_str: $m_count message(s)");
218 unless ($server = __PACKAGE__->remote_account($account, 1)) { # assignment, not comparison
219 $logger->error("Failed remote account connection for $log_str");
222 foreach (@messageset) {
223 $_ or next; # we already warned about bum ids
226 $error = "Server error: Failed remote account connection for $log_str"; # already told $logger, this is to update object below
227 } elsif (! $_->edi) {
228 $logger->error("Message (id " . $_->id. ") for $log_str has no EDI content");
229 $error = "EDI empty!";
230 } elsif ($res = $server->put({remote_path => $account->path, content => $_->edi, single_ext => 1})) {
231 # This is the successful case!
232 $_->remote_file($res);
233 $_->status('complete');
234 $_->process_time('NOW'); # For outbound files, sending is the end of processing on the EG side.
235 $logger->info("Sent message (id " . $_->id. ") via $log_str");
237 $logger->error("(S)FTP put to $log_str FAILED: " . ($server->error || 'UNKOWNN'));
238 $error = "put FAILED: " . ($server->error || 'UNKOWNN');
242 $_->error_time('NOW');
244 $logger->info("Calling update_acq_edi_message");
246 unless ($e->update_acq_edi_message($_)) {
247 $logger->error("EDI send_core update_acq_edi_message failed for message object: " . Dumper($_));
248 OpenILS::Application::Acq::EDI::Translator->debug_file(Dumper($_ ), '/tmp/update_acq_edi_message.FAIL');
249 OpenILS::Application::Acq::EDI::Translator->debug_file(Dumper($_->to_bare_hash), '/tmp/update_acq_edi_message.FAIL.to_bare_hash');
251 # There's always an update, even if we failed.
253 __PACKAGE__->record_activity($account, $e); # There's always an update, even if we failed.
258 # attempt_translation does not touch the DB, just the object.
259 sub attempt_translation {
260 my ($class, $edi_message, $to_edi) = @_;
261 my $tran = translator();
262 my $ret = $to_edi ? $tran->json2edi($edi_message->jedi) : $tran->edi2json($edi_message->edi);
263 # $logger->error("json: " . Dumper($json)); # debugging
264 if (not $ret or (! ref($ret)) or $ret->is_fault) { # RPC::XML::fault on failure
265 $edi_message->status('trans_error');
266 $edi_message->error_time('NOW');
267 my $pre = "EDI Translator " . ($to_edi ? 'json2edi' : 'edi2json') . " failed";
268 my $message = ref($ret) ?
269 ("$pre, Error " . $ret->code . ": " . __PACKAGE__->nice_string($ret->string)) :
270 ("$pre: " . __PACKAGE__->nice_string($ret) ) ;
271 $edi_message->error($message);
272 $logger->error( $message);
275 $edi_message->status('translated');
276 $edi_message->translate_time('NOW');
278 $edi_message->edi($ret->value); # translator returns an object
280 $edi_message->jedi($ret->value); # translator returns an object
285 sub retrieve_vendors {
286 my ($self, $e, $vendor_id, $last_activity) = @_; # $e is a working editor
290 my $criteria = {'+acqpro' => {active => 't'}};
291 $criteria->{'+acqpro'}->{id} = $vendor_id if $vendor_id;
292 return $e->search_acq_edi_account([
297 acqedi => ['provider']
301 # {"id":{"!=":null},"+acqpro":{"active":"t"}}, {"join":"acqpro", "flesh_fields":{"acqedi":["provider"]},"flesh":1}
304 # This is the SRF-exposed call, so it does checkauth
307 my ($self, $conn, $auth, $vendor_id, $last_activity, $max) = @_;
309 my $e = new_editor(authtoken=>$auth);
310 unless ($e and $e->checkauth()) {
311 $logger->warn("checkauth failed for authtoken '$auth'");
314 # return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency); # add permission here ?
316 my $set = __PACKAGE__->retrieve_vendors($e, $vendor_id, $last_activity) or return $e->die_event;
317 return __PACKAGE__->retrieve_core($e, $set, $max);
321 # field_map takes the hashref of vendor data with fields from acq.edi_account and
322 # maps them to the argument style needed for RemoteAccount. It also extrapolates
323 # data from the remote_host string for type and port, when available.
327 my $vendor = shift or return;
328 my $no_override = @_ ? shift : 0;
330 $verbose and $logger->warn("vendor: " . Dumper($vendor));
331 foreach (keys %map) {
332 $args{$map{$_}} = $vendor->$_ if defined $vendor->$_;
334 unless ($no_override) {
335 $args{remote_path} = $vendor->in_dir; # override "path" with "in_dir"
337 my $host = $args{remote_host} || '';
338 ($host =~ s/^(S?FTP)://i and $args{type} = uc($1)) or
339 ($host =~ s/^(SSH|SCP)://i and $args{type} = 'SCP' ) ;
340 $host =~ s/:(\d+)$// and $args{port} = $1;
341 ($args{remote_host} = $host) =~ s#/+##;
342 $verbose and $logger->warn("field_map: " . Dumper(\%args));
347 # The point of remote_account is to get the RemoteAccount object with args from the DB
350 my ($self, $vendor, $outbound, $e) = @_;
352 unless (ref($vendor)) { # It's not a hashref/object.
353 $vendor or return; # If in fact it's nothing: abort!
354 # else it's a vendor_id string, so get the full vendor data
356 my $set_of_one = $self->retrieve_vendors($e, $vendor) or return;
357 $vendor = shift @$set_of_one;
360 return OpenILS::Utils::RemoteAccount->new(
361 $self->field_map($vendor, $outbound)
365 # takes account ID or account Fieldmapper object
367 sub record_activity {
368 my ($class, $account_or_id, $e) = @_;
369 $account_or_id or return;
371 my $account = ref($account_or_id) ? $account_or_id : $e->retrieve_acq_edi_account($account_or_id);
372 $logger->info("EDI record_activity calling update_acq_edi_account");
373 $account->last_activity('NOW') or return;
375 $e->update_acq_edi_account($account) or $logger->warn("EDI: in record_activity, update_acq_edi_account FAILED");
382 my $string = shift or return '';
384 my $head = @_ ? shift : 100;
385 my $tail = @_ ? shift : 25;
386 (length($string) < $head + $tail) and return $string;
387 my $h = substr($string,0,$head);
388 my $t = substr($string, -1*$tail);
392 # return substr($string,0,$head) . "... " . substr($string, -1*$tail);
396 my ($class, $jedi) = @_;
398 my $msg = OpenSRF::Utils::JSON->JSON2perl( $jedi );
399 open (FOO, ">>/tmp/JSON2perl_dump.txt");
400 print FOO Dumper($msg), "\n\n";
402 $logger->warn("Dumped JSON2perl to /tmp/JSON2perl_dump.txt");
406 our @datecodes = (35, 359, 17, 191, 69, 76, 75, 79, 85, 74, 84, 223);
407 our @noop_6063 = (21);
409 # ->process_jedi($message, $server, $remote, $e)
410 # $message is an edi_message object
413 my ($class, $message, $server, $remote, $e) = @_;
415 $server ||= {}; # context
416 $remote ||= {}; # context
419 unless (ref($message) and $jedi = $message->jedi) { # assignment, not comparison
420 $logger->warn("EDI process_jedi missing required argument (edi_message object with jedi)!");
423 my $perl = __PACKAGE__->jedi2perl($jedi);
425 if (ref($message) and not $perl) {
426 $error = ($message->error || '') . " JSON2perl (jedi2perl) FAILED to convert jedi";
428 elsif (! $perl->{body}) {
429 $error = "EDI interchange body not found!";
431 elsif (! $perl->{body}->[0]) {
432 $error = "EDI interchange body not a populated arrayref!";
435 $logger->warn($error);
436 $message->error($error);
437 $message->error_time('NOW');
439 $e->update_acq_edi_message($message) or $logger->warn("EDI update_acq_edi_message failed! $!");
444 # Crazy data structure. Most of the arrays will be 1 element... we think.
446 # {'body' => [{'ORDERS' => [['UNH',{'0062' => '4635','S009' => {'0057' => 'EAN008','0051' => 'UN','0052' => 'D','0065' => 'ORDERS', ...
448 # So you might access it like:
449 # $obj->{body}->[0]->{ORDERS}->[0]->[0] eq 'UNH'
451 $logger->info("EDI interchange body has " . scalar(@{$perl->{body}}) . " message(s)");
452 my @ok_msg_codes = qw/ORDRSP OSTRPT/;
455 foreach my $part (@{$perl->{body}}) {
457 unless (ref $part and scalar keys %$part) {
458 $logger->warn("EDI interchange message $i lacks structure. Skipping it.");
461 foreach my $key (keys %$part) {
462 if (! grep {$_ eq $key} @ok_msg_codes) { # We only do one type for now. TODO: other types here
463 $logger->warn("EDI interchange $i contains unhandled '$key' message. Ignoring it.");
466 my $msg = __PACKAGE__->message_object($part->{$key}) or next;
467 push @messages, $msg;
469 my $bgm = $msg->xpath('BGM') or $logger->warn("EDI No BGM segment found?!");
470 my $tag4343 = $msg->xpath('BGM/4343');
471 my $tag1225 = $msg->xpath('BGM/1225');
473 $logger->info(sprintf "EDI $key BGM/4343 Response Type: %s - %s", $tag4343->value, $tag4343->label)
475 $logger->warn("EDI $key BGM/4343 Response Type Code unrecognized"); # next; #?
478 $logger->info(sprintf "EDI $key BGM/1225 Message Function: %s - %s", $tag1225->value, $tag1225->label);
480 $logger->warn("EDI $key BGM/1225 Message Function Code unrecognized"); # next; #?
483 # TODO: currency check, just to be paranoid
484 # *should* be unnecessary (vendor should reply in currency we send in ORDERS)
485 # That begs a policy question: how to handle mismatch? convert (bad accuracy), reject, or ignore? I say ignore.
487 # ALL those codes below are basically some form of (lastest) delivery date/time
488 # see, e.g.: http://www.stylusstudio.com/edifact/D04B/2005.htm
489 # The order is the order of definitiveness (first match wins)
490 # Note: if/when we do serials via EDI, dates (and ranges/periods) will need massive special handling
494 foreach my $date ($msg->xpath('delivery_schedule')) {
495 my $val_2005 = $date->xpath_value('DTM/2005') or next;
496 (grep {$val_2005 eq $_} @datecodes) or next; # no match means some other kind of date we don't care about
500 DATECODE: foreach my $dcode (@datecodes) { # now cycle back through hits in order of dcode definitiveness
501 foreach my $date (@dates) {
502 $date->xpath_value('DTM/2005') == $dcode or next;
503 $ddate = $date->xpath_value('DTM/2380') and last DATECODE;
504 # TODO: conversion based on format specified in DTM/2379 (best encapsulated in Business::EDI)
508 foreach my $detail ($msg->part('line_detail')) {
509 my $eg_line = __PACKAGE__->eg_li($detail, $remote, $server->{remote_host}, $e) or next;
510 my $li_date = $detail->xpath_value('DTM/2380') || $ddate;
511 my $price = $detail->xpath_value('line_price/PRI/5118') || '';
512 $eg_line->expected_recv_time($li_date) if $li_date;
513 $eg_line->estimated_unit_price($price) if $price;
514 if (not $message->purchase_order) { # first good lineitem sets the message PO link
515 $message->purchase_order($eg_line->purchase_order); # EG $message object NOT Business::EDI $msg object
517 $e->update_acq_edi_message($message) or $logger->warn("EDI update_acq_edi_message (for PO number) failed! $!");
520 # $e->search_acq_edi_account([]);
522 my $eg_lids = $e->search_acq_lineitem_detail({lineitem => $eg_line->id}); # should be the same as $eg_line->lineitem_details
523 my $lidcount = scalar(@$eg_lids);
524 $lidcount == $eg_line->item_count or $logger->warn(
525 sprintf "EDI: LI %s itemcount (%d) mismatch, %d LIDs found", $eg_line->id, $eg_line->item_count, $lidcount
527 foreach my $qty ($detail->part('all_QTY')) {
528 my $ubound = $qty->xpath_value('6060') or next; # nothing to do if qty is 0
529 my $val_6063 = $qty->xpath_value('6063');
530 $ubound > 0 or next; # don't be crazy!
532 $logger->warn("EDI: Response for LI " . $eg_line->id . " specifies quantity $ubound with no 6063 code! Contact vendor to resolve.");
536 my $eg_reason = $e->retrieve_acq_cancel_reason(1200 + $val_6063); # DB populated w/ 6063 keys in 1200's
538 $logger->warn("EDI: Unhandled quantity code '$val_6063' (LI " . $eg_line->id . ") $ubound items unprocessed");
540 } elsif (grep {$val_6063 == $_} @noop_6063) { # an FYI like "ordered quantity"
542 or $logger->warn("EDI: LI " . $eg_line->id . " -- Vendor says we ordered $ubound, but we have $lidcount LIDs!)");
545 # elsif ($val_6063 == 83) { # backorder
546 #} elsif ($val_6063 == 85) { # cancel
547 #} elsif ($val_6063 == 12 or $val_6063 == 57 or $val_6063 == 84 or $val_6063 == 118) {
548 # despatched, in transit, urgent delivery, or quantity manifested
550 if ($touches >= $lidcount) {
551 $logger->warn("EDI: LI " . $eg_line->id . ", We already updated $touches of $lidcount LIDS, " .
552 "but message wants QTY $ubound more set to " . $eg_reason->label . ". Ignoring!");
556 foreach (1 .. $ubound) {
557 my $eg_lid = shift @$eg_lids or $logger->warn("EDI: Used up all $lidcount LIDs! Ignoring extra status " . $eg_reason->label);
559 $logger->debug(sprintf "Updating LID %s to %s", $eg_lid->id, $eg_reason->label);
560 $eg_lid->cancel_reason($eg_reason->id);
561 $e->update_acq_lineitem_detail($eg_lid);
565 if ($ubound == $eg_line->item_count) {
566 $eg_line->cancel_reason($eg_reason->id); # if ALL the items have the same cancel_reason, the PO gets it too
569 $eg_line->edit_time('NOW'); # TODO: have this field automatically updated via ON UPDATE trigger.
571 $e->update_acq_lineitem($eg_line) or $logger->warn("EDI: update_acq_lineitem FAILED");
573 # print STDERR "Lineitem update: ", Dumper($eg_line);
580 # returns message object if processing should continue
581 # returns false/undef value if processing should abort
585 my $body = shift or return;
586 my $key = shift if @_;
587 my $keystring = $key || 'UNSPECIFIED';
589 my $msg = Business::EDI::Message->new($body);
591 $logger->error("EDI interchange message: $keystring body failed Business::EDI constructor. Skipping it.");
594 $key = $msg->code if ! $key; # Now we set the key for reference if it wasn't specified
595 my $val_0065 = $msg->xpath_value('UNH/S009/0065') || '';
596 unless ($val_0065 eq $key) {
597 $logger->error("EDI $key UNH/S009/0065 ('$val_0065') conflicts w/ message type $key. Aborting");
600 my $val_0051 = $msg->xpath_value('UNH/S009/0051') || '';
601 unless ($val_0051 eq 'UN') {
602 $logger->warn("EDI $key UNH/S009/0051 designates '$val_0051', not 'UN' as controlling agency. Attempting to process anyway");
604 my $val_0054 = $msg->xpath_value('UNH/S009/0054') || '';
606 $logger->info("EDI $key UNH/S009/0054 uses Spec revision version '$val_0054'");
607 # Possible Spec Version limitation
608 # my $yy = $tag_0054 ? substr($val_0054,0,2) : '';
609 # unless ($yy eq '00' or $yy > 94 ...) {
610 # $logger->warn("EDI $key UNH/S009/0051 Spec revision version '$val_0054' not supported");
613 $logger->warn("EDI $key UNH/S009/0054 does not reference a known Spec revision version");
618 =head2 ->eg_li($lineitem_object, [$remote, $server_log_string, $editor])
620 my $line_item = OpenILS::Application::Acq::EDI->eg_li($edi_line, $remote, "test_server_01", $e);
622 $remote is a acq.edi_account Fieldmapper object.
623 $server_log_string is an arbitrary string use to identify the remote host in potential log messages.
626 acq.lineitem.estimated_unit_price,
627 acq.lineitem.state (dependent on mapping codes),
628 acq.lineitem.expected_recv_time,
629 acq.lineitem.edit_time (consequently)
634 my ($class, $line, $server, $server_log_string, $e) = @_;
639 # my $rff = $line->part('line_reference/RFF') or $logger->warn("EDI ORDRSP line_detail/RFF missing!");
640 my $val_1153 = $line->xpath_value('line_reference/RFF/1153') || '';
641 my $val_1154 = $line->xpath_value('line_reference/RFF/1154') || '';
642 my $val_1082 = $line->xpath_value('LIN/1082') || '';
646 $val_1154 =~ s#^(.*)\/##; # Many sources send the ID as 'order_ID/LI_ID'
647 $1 and push @po_nums, $1;
648 $val_1082 =~ s#^(.*)\/##; # Many sources send the ID as 'order_ID/LI_ID'
649 $1 and push @po_nums, $1;
651 # TODO: possible check of po_nums
652 # now do a lot of checking
654 if ($val_1153 eq 'LI') {
655 $id = $val_1154 or $logger->warn("EDI ORDRSP RFF/1154 reference to LI empty. Attempting failover to LIN/1082");
657 $logger->warn("EDI ORDRSP RFF/1153 unexpected value ('$val_1153', not 'LI'). Attempting failover to LIN/1082");
660 # FIXME - the line item ID in LIN/1082 ought to match RFF/1154, but
661 # not all materials vendors obey this. Commenting out check for now
662 # as being too strict.
663 #if ($id and $val_1082 and $val_1082 ne $id) {
664 # $logger->warn("EDI ORDRSP LIN/1082 Line Item ID mismatch ($id vs. $val_1082): cannot target update");
668 $id ||= $val_1082 || '';
670 $logger->warn('Cannot identify line item from EDI message');
674 $logger->info("EDI retrieve/update lineitem $id");
676 my $li = OpenILS::Application::Acq::Lineitem::retrieve_lineitem_impl($e, $id, {
677 flesh_li_details => 1,
678 }, 1); # Could send more {options}. The 1 is for no_auth.
680 if (! $li or ref($li) ne 'Fieldmapper::acq::lineitem') {
681 $logger->error("EDI failed to retrieve lineitem by id '$id' for server $server_log_string");
684 unless ((! $server) or (! $server->provider)) { # but here we want $server to be acq.edi_account instead of RemoteAccount
685 if ($server->provider != $li->provider) {
686 # links go both ways: acq.provider.edi_default and acq.edi_account.provider
687 $logger->info("EDI acct provider (" . $server->provider. ") doesn't match lineitem provider("
688 . $li->provider . "). Checking acq.provider.edi_default...");
689 my $provider = $e->retrieve_acq_provider($li->provider);
690 if ($provider->edi_default != $server->id) {
691 $logger->error(sprintf "EDI provider/acct %s/%s (%s) is blocked from updating lineitem $id belonging to provider/edi_default %s/%s",
692 $server->provider, $server->id, $server->label, $li->provider, $provider->edi_default);
698 my @lin_1229 = $line->xpath('LIN/1229') or $logger->warn("EDI LIN/1229 Action Code missing!");
699 my $key = $lin_1229[0] or return;
701 my $eg_reason = $e->retrieve_acq_cancel_reason(1000 + $key->value); # DB populated w/ spec keys in 1000's
702 $eg_reason or $logger->warn(sprintf "EDI LIN/1229 Action Code '%s' (%s) not recognized in acq.cancel_reason", $key->value, $key->label);
703 $eg_reason or return;
705 $li->cancel_reason($eg_reason->id);
706 unless ($eg_reason->keep_debits) {
707 $logger->warn("EDI LIN/1229 Action Code '%s' (%s) has keep_debits=0", $key->value, $key->label);
710 my @prices = $line->xpath_value("line_price/PRI/5118");
711 $li->estimated_unit_price($prices[0]) if @prices;
716 # caching not needed for now (edi_fetcher is asynchronous)
718 # my ($class, $key, $e) = @_;
719 # $reasons->{$key} and return $reasons->{$key};
720 # $e ||= new_editor();
721 # $reasons->{$key} = $e->retrieve_acq_cancel_reason($key);
722 # return $reasons->{$key};
731 Note the pseudo-hash 2-element arrays.
742 '7140' => '9780446360272',
754 'NOT APPLIC WEBSTERS NEW WORLD THESA'