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::Application::Acq::Invoice;
15 use OpenILS::Utils::RemoteAccount;
16 use OpenILS::Utils::CStoreEditor q/new_editor/;
17 use OpenILS::Utils::Fieldmapper;
18 use OpenILS::Application::Acq::EDI::Translator;
19 use OpenILS::Application::AppUtils;
20 my $U = 'OpenILS::Application::AppUtils';
22 use OpenILS::Utils::EDIReader;
28 my($class, %args) = @_;
29 my $self = bless(\%args, $class);
34 # our $reasons = {}; # cache for acq.cancel_reason rows ?
39 return $translator ||= OpenILS::Application::Acq::EDI::Translator->new(@_);
43 host => 'remote_host',
44 username => 'remote_user',
45 password => 'remote_password',
46 account => 'remote_account',
47 # in_dir => 'remote_path', # field_map overrides path with in_dir
48 path => 'remote_path',
51 my $VENDOR_KLUDGE_MAP = {
53 amount_billed_is_per_unit => [1699342]
60 __PACKAGE__->register_method(
62 api_name => 'open-ils.acq.edi.retrieve',
65 desc => 'Fetch incoming message(s) from EDI accounts. ' .
66 'Optional arguments to restrict to one vendor and/or a max number of messages. ' .
67 'Note that messages are not parsed or processed here, just fetched and translated.',
69 {desc => 'Authentication token', type => 'string'},
70 {desc => 'Vendor ID (undef for "all")', type => 'number'},
71 {desc => 'Date Inactive Since', type => 'string'},
72 {desc => 'Max Messages Retrieved', type => 'number'}
75 desc => 'List of new message IDs (empty if none)',
82 my ($self, $set, $max, $e, $test) = @_; # $e is a working editor
85 $set ||= __PACKAGE__->retrieve_vendors($e);
89 foreach my $account (@$set) {
93 "EDI check for vendor " .
94 ++$vcount . " of " . scalar(@$set) . ": " . $account->host
96 unless ($server = __PACKAGE__->remote_account($account)) { # assignment
98 sprintf "Failed remote account mapping for %s (%s)",
99 $account->host, $account->id
104 if ($account->in_dir) {
105 if ($account->in_dir =~ /\*+.*\//) {
107 "EDI in_dir has a slash after an asterisk in value: '" .
109 "'. Skipping account with indeterminate target dir!"
115 my @files = ($server->ls({remote_file => ($account->in_dir || './')}));
116 my @ok_files = grep {$_ !~ /\/\.?\.$/ and $_ ne '0'} @files;
117 $logger->info(sprintf "%s of %s files at %s/%s", scalar(@ok_files), scalar(@files), $account->host, $account->in_dir || "");
119 foreach my $remote_file (@ok_files) {
120 my $description = sprintf "%s/%s", $account->host, $remote_file;
122 # deduplicate vs. acct/filenames already in DB.
124 # The reason we match against host/username/password/in_dir
125 # is that there may be many variant accounts that point to the
126 # same FTP site and credentials. If we only checked based on
127 # acq.edi_account.id, we'd not find out in those cases that we've
128 # already processed the same file before.
129 my $hits = $e->search_acq_edi_message(
133 host => $account->host,
134 username => $account->username,
135 password => $account->password,
136 in_dir => $account->in_dir
138 remote_file => {'=' => {
139 transform => 'evergreen.lowercase',
140 value => ['evergreen.lowercase', $remote_file]
142 status => {'in' => [qw/ processed proc_error trans_error /]},
144 { join => {"acqedi" => {}}, limit => 1 }
149 my $msg = "EDI: test for already-retrieved files yielded " .
150 "event " . $e->event->{textcode};
153 return $e->die_event;
157 $logger->debug("EDI: $remote_file already retrieved. Skipping");
158 warn "EDI: $remote_file already retrieved. Skipping";
163 if ($max and $count > $max) {
168 sprintf "%s of %s targets: %s",
169 $count, scalar(@ok_files), $description
171 printf("%d of %d targets: %s\n", $count, scalar(@ok_files), $description);
173 push @return, "test_$count";
177 my $io = IO::Scalar->new(\$content);
180 $server->get({remote_file => $remote_file, local_file => $io})
182 $logger->error("(S)FTP get($description) failed");
186 my $incoming = __PACKAGE__->process_retrieval(
187 $content, $remote_file, $server, $account->id
190 push @return, @$incoming;
197 # procses_retrieval() returns a reference to a list of acq.edi_message IDs
198 sub process_retrieval {
199 my ($class, $content, $filename, $server, $account_or_id) = @_;
203 my $account = __PACKAGE__->record_activity($account_or_id, $e);
205 # a single EDI blob can contain multiple messages
206 # create one edi_message per included message
208 my $messages = OpenILS::Utils::EDIReader->new->read($content);
211 for my $msg_hash (@$messages) {
213 my $incoming = Fieldmapper::acq::edi_message->new;
215 $incoming->remote_file($filename);
216 $incoming->account($account->id);
217 $incoming->edi($content);
218 $incoming->message_type($msg_hash->{message_type});
219 $incoming->jedi(OpenSRF::Utils::JSON->perl2JSON($msg_hash)); # jedi-2.0
220 $incoming->status('translated');
221 $incoming->translate_time('NOW');
223 if ($msg_hash->{purchase_order}) {
224 # Some vendors just put their name where there ought to be a number,
225 # and others put alphanumeric strings that mean nothing to us, so
226 # we sure won't match a PO in the system this way. We can pick
227 # up PO number later from the lineitems themselves if necessary.
229 if ($msg_hash->{purchase_order} !~ /^\d+$/) {
230 $logger->warn("EDI: PO identifier is non-numeric. Blanking and continuing.");
231 undef $msg_hash->{purchase_order};
233 $logger->info("EDI: processing message for PO " .
234 $msg_hash->{purchase_order});
235 $incoming->purchase_order($msg_hash->{purchase_order});
236 unless ($e->retrieve_acq_purchase_order(
237 $incoming->purchase_order)) {
238 $logger->warn("EDI: received order response for " .
239 "nonexistent PO. Skipping...");
246 unless($e->create_acq_edi_message($incoming)) {
247 $logger->error("EDI: unable to create edi_message " . $e->die_event);
250 # refresh to pickup create_date, etc.
251 $incoming = $e->retrieve_acq_edi_message($incoming->id);
254 # since there's a fair chance of unhandled problems
255 # cropping up, particularly with new vendors, wrap w/ eval.
256 eval { $class->process_parsed_msg($account, $incoming, $msg_hash) };
260 $incoming = $e->retrieve_acq_edi_message($incoming->id);
262 $incoming->status('proc_error');
263 $incoming->error_time('now');
264 $incoming->error($@);
266 $incoming->status('processed');
268 $e->update_acq_edi_message($incoming);
271 push(@return, $incoming->id);
278 # $account is a Fieldmapper object for acq.edi_account row
279 # $message_ids is an arrayref with acq.edi_message.id values
280 # $e is optional editor object
282 my ($class, $account, $message_ids, $e) = @_; # $e is a working editor
284 return unless $account and @$message_ids;
288 my @messageset = map {$e->retrieve_acq_edi_message($_)} @$message_ids;
290 my $m_count = scalar(@messageset);
291 if (@$message_ids != $m_count) {
292 $logger->warn(scalar(@$message_ids) - $m_count . " bad IDs passed to send_core (ignored)");
295 my $log_str = sprintf "EDI send to edi_account %s (%s)", $account->id, $account->host;
296 $logger->info("$log_str: $m_count message(s)");
297 return unless $m_count;
301 unless ($server = __PACKAGE__->remote_account($account, 1)) { # assignment
302 $logger->error("Failed remote account connection for $log_str");
306 foreach (@messageset) {
307 $_ or next; # we already warned about bum ids
310 # We already told $logger; this is to update object below
311 $error = "Server error: Failed remote account connection ".
313 } elsif (! $_->edi) {
315 "Message (id " . $_->id. ") for $log_str has no EDI content"
317 $error = "EDI empty!";
319 $res = $server->put({
320 remote_path => $account->path, content => $_->edi,
324 # This is the successful case!
325 $_->remote_file($res);
326 $_->status('complete');
327 $_->process_time('NOW');
329 # For outbound files, sending is the end of processing on
332 $logger->info("Sent message (id " . $_->id. ") via $log_str");
335 "(S)FTP put to $log_str FAILED: " .
336 ($server->error || 'UNKOWNN')
338 $error = "put FAILED: " . ($server->error || 'UNKOWNN');
343 $_->error_time('NOW');
346 $logger->info("Calling update_acq_edi_message");
349 unless ($e->update_acq_edi_message($_)) {
351 "EDI send_core update_acq_edi_message failed " .
352 "for message object: " . Dumper($_)
355 OpenILS::Application::Acq::EDI::Translator->debug_file(
357 '/tmp/update_acq_edi_message.FAIL'
359 OpenILS::Application::Acq::EDI::Translator->debug_file(
360 Dumper($_->to_bare_hash),
361 '/tmp/update_acq_edi_message.FAIL.to_bare_hash'
365 # There's always an update, even if we failed.
367 __PACKAGE__->record_activity($account, $e);
372 # attempt_translation does not touch the DB, just the object.
373 sub attempt_translation {
374 my ($class, $edi_message, $to_edi) = @_;
376 my $ret = $to_edi ? translator->json2edi($edi_message->jedi) :
377 translator->edi2json($edi_message->edi);
379 if (not $ret or (! ref($ret)) or $ret->is_fault) {
380 # RPC::XML::fault on failure
382 $edi_message->status('trans_error');
383 $edi_message->error_time('NOW');
384 my $pre = "EDI Translator " .
385 ($to_edi ? 'json2edi' : 'edi2json') . " failed";
387 my $message = ref($ret) ?
388 ("$pre, Error " . $ret->code . ": " .
389 __PACKAGE__->nice_string($ret->string)) :
390 ("$pre: " . __PACKAGE__->nice_string($ret)) ;
392 $edi_message->error($message);
393 $logger->error($message);
397 $edi_message->status('translated');
398 $edi_message->translate_time('NOW');
401 $edi_message->edi($ret->value); # translator returns an object
403 $edi_message->jedi($ret->value); # translator returns an object
409 sub retrieve_vendors {
410 my ($self, $e, $vendor_id, $last_activity) = @_; # $e is a working editor
414 my $criteria = {'+acqpro' => {active => 't'}};
415 $criteria->{'+acqpro'}->{id} = $vendor_id if $vendor_id;
416 return $e->search_acq_edi_account([
421 acqedi => ['provider']
427 # This is the SRF-exposed call, so it does checkauth
430 my ($self, $conn, $auth, $vendor_id, $last_activity, $max) = @_;
432 my $e = new_editor(authtoken=>$auth);
433 unless ($e and $e->checkauth()) {
434 $logger->warn("checkauth failed for authtoken '$auth'");
437 # return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency); # add permission here ?
439 my $set = __PACKAGE__->retrieve_vendors($e, $vendor_id, $last_activity) or return $e->die_event;
440 return __PACKAGE__->retrieve_core($e, $set, $max);
444 # field_map takes the hashref of vendor data with fields from acq.edi_account and
445 # maps them to the argument style needed for RemoteAccount. It also extrapolates
446 # data from the remote_host string for type and port, when available.
450 my $vendor = shift or return;
451 my $no_override = @_ ? shift : 0;
453 $verbose and $logger->warn("vendor: " . Dumper($vendor));
454 foreach (keys %map) {
455 $args{$map{$_}} = $vendor->$_ if defined $vendor->$_;
457 unless ($no_override) {
458 $args{remote_path} = $vendor->in_dir; # override "path" with "in_dir"
460 my $host = $args{remote_host} || '';
461 ($host =~ s/^(S?FTP)://i and $args{type} = uc($1)) or
462 ($host =~ s/^(SSH|SCP)://i and $args{type} = 'SCP' ) ;
463 $host =~ s/:(\d+)$// and $args{port} = $1;
464 ($args{remote_host} = $host) =~ s#/+##;
465 $verbose and $logger->warn("field_map: " . Dumper(\%args));
470 # The point of remote_account is to get the RemoteAccount object with args from the DB
473 my ($self, $vendor, $outbound, $e) = @_;
475 unless (ref($vendor)) { # It's not a hashref/object.
476 $vendor or return; # If in fact it's nothing: abort!
477 # else it's a vendor_id string, so get the full vendor data
479 my $set_of_one = $self->retrieve_vendors($e, $vendor) or return;
480 $vendor = shift @$set_of_one;
483 return OpenILS::Utils::RemoteAccount->new(
484 $self->field_map($vendor, $outbound)
488 # takes account ID or account Fieldmapper object
490 sub record_activity {
491 my ($class, $account_or_id, $e) = @_;
492 $account_or_id or return;
494 my $account = ref($account_or_id) ? $account_or_id : $e->retrieve_acq_edi_account($account_or_id);
495 $logger->info("EDI record_activity calling update_acq_edi_account");
496 $account->last_activity('NOW') or return;
498 $e->update_acq_edi_account($account) or $logger->warn("EDI: in record_activity, update_acq_edi_account FAILED");
505 my $string = shift or return '';
507 my $head = @_ ? shift : 100;
508 my $tail = @_ ? shift : 25;
509 (length($string) < $head + $tail) and return $string;
510 my $h = substr($string,0,$head);
511 my $t = substr($string, -1*$tail);
515 # return substr($string,0,$head) . "... " . substr($string, -1*$tail);
518 # process_message_buyer() is used in processing both INVOIC
519 # messages as well as ORDRSP ones. As such, the $eg_inv parameter is
521 sub process_message_buyer {
522 my ($class, $e, $msg_hash, $message, $log_prefix, $eg_inv) = @_;
524 my $vendcode = $msg_hash->{buyer_code};
526 # some vendors encode the account number as the SAN.
527 # starting with the san value, then the account value,
528 # treat each as a san, then an acct number until the first success
529 for my $buyer ( ($msg_hash->{buyer_san}, $msg_hash->{buyer_acct}) ) {
532 # some vendors encode the SAN as "$SAN $vendcode"
534 ($buyer, $vendcode) = $buyer =~ /(\S+)\s*(\S+)?$/;
537 my $addr = $e->search_actor_org_address(
538 {valid => "t", san => $buyer})->[0];
542 $eg_inv->receiver($addr->org_unit) if $eg_inv;
544 my $orig_acct = $e->retrieve_acq_edi_account($message->account);
546 if (defined($vendcode) and ($orig_acct->vendcode ne $vendcode)) {
547 # The vendcode can give us the opportunity to change the
548 # acq.edi_account with which our acq.edi_message is associated
549 # in case it's wrong.
551 my $other_accounts = $e->search_acq_edi_account(
553 vendcode => $vendcode,
554 host => $orig_acct->host,
555 username => $orig_acct->username,
556 password => $orig_acct->password,
557 in_dir => $orig_acct->in_dir
561 if (@$other_accounts) {
562 # We can update this object because the caller saves
563 # it with cstore later.
564 $message->account($other_accounts->[0]->id);
567 $log_prefix . sprintf(
568 "changing edi_account from %d to %d based on " .
569 "vendcode '%s' (%d match(es))",
570 $orig_acct->id, $message->account, $vendcode,
571 scalar(@$other_accounts)
575 # If we've updated the message's account, and if we're
576 # dealing with an invoice, we should update the invoice's
577 # provider and shipper fields. XXX what's the difference
578 # between shipper and provider, really?
581 $eg_inv->shipper($other_accounts->[0]->provider)
591 my $accts = $e->search_acq_edi_account({vendacct => $buyer});
594 if (grep { $_->id == $message->account } @$accts) {
596 $log_prefix . sprintf(
597 "Not changing edi_account because we found " .
598 "(%d) matching vendacct(s), one of which " .
599 "being on the edi_account we already had",
606 $log_prefix . sprintf(
607 "changing edi_account from %d to %d based on " .
608 "vendacct '%s' (%d match(es))",
609 $message->account, $accts->[0]->id, $buyer,
614 # Both $message and $eg_inv should be saved later by the caller.
615 $message->account($accts->[0]->id);
617 $eg_inv->receiver($accts->[0]->owner);
619 $eg_inv->shipper($accts->[0]->provider)
629 # parts of this process can fail without the entire
630 # thing failing. If a catastrophic error occurs,
631 # it will occur via die.
632 sub process_parsed_msg {
633 my ($class, $account, $incoming, $msg_hash) = @_;
636 if ($incoming->message_type eq 'INVOIC') {
637 return $class->create_acq_invoice_from_edi(
638 $msg_hash, $account->provider, $incoming);
643 # First do this for the whole message...
644 $class->process_message_buyer(
645 new_editor, $msg_hash, $incoming, "ORDRSP processing"
648 # ... now do this stuff per-lineitem.
649 for my $li_hash (@{$msg_hash->{lineitems}}) {
650 my $e = new_editor(xact => 1);
652 my $li_id = $li_hash->{id};
653 my $li = $e->retrieve_acq_lineitem($li_id);
656 $logger->error("EDI: request for invalid lineitem ID '$li_id'");
661 $li->expected_recv_time(
662 $class->edi_date_to_iso($li_hash->{expected_date}));
664 $li->estimated_unit_price($li_hash->{unit_price});
666 if (not $incoming->purchase_order) {
667 # PO should come from the EDI message, but if not...
669 # NOTE: We used to refetch $incoming here, but that discarded
670 # changes made by process_message_buyer() above, and is not
671 # necessary since our caller just did that before invoking us.
673 $incoming->purchase_order($li->purchase_order);
675 # NOTE: $li *just* came from the database, so if this update fails
676 # we should actually die() and thereby abort any changes from this
677 # entire message, because something weird is happening.
679 "EDI: unable to update edi_message ". $e->die_event->{textcode}
680 ) unless $e->update_acq_edi_message($incoming);
683 my $lids = $e->json_query({
684 select => {acqlid => ['id']},
686 where => {lineitem => $li->id}
689 my @lids = map { $_->{id} } @$lids;
690 my $lid_count = scalar(@lids);
691 my $lids_covered = 0;
692 my $lids_cancelled = 0;
696 for my $qty (@{$li_hash->{quantities}}) {
698 my $qty_count = $qty->{quantity};
699 my $qty_code = $qty->{code};
701 next unless defined $qty_count;
704 $logger->warn("EDI: Response for LI $li_id specifies quantity ".
705 "$qty_count with no 6063 code! Contact vendor to resolve.");
709 $logger->info("EDI: LI $li_id processing quantity count=$qty_count / code=$qty_code");
711 if ($qty_code eq '21') { # "ordered quantity"
712 $order_qty = $qty_count;
713 $logger->info("EDI: LI $li_id -- vendor confirms $qty_count ordered");
714 $logger->warn("EDI: LI $li_id -- order count $qty_count ".
715 "does not match LID count $lid_count") unless $qty_count == $lid_count;
719 $lids_covered += $qty_count;
721 if ($qty_code eq '12') {
722 $dispatch_qty = $qty_count;
723 $logger->info("EDI: LI $li_id -- vendor dispatched $qty_count");
726 } elsif ($qty_code eq '57') {
727 $logger->info("EDI: LI $li_id -- $qty_count in transit");
730 # 84: urgent delivery
731 # 118: quantity manifested
734 # -------------------------------------------------------------------------
735 # All of the remaining quantity types require that we apply a cancel_reason
736 # DB populated w/ 6063 keys in 1200's
738 my $eg_reason = $e->retrieve_acq_cancel_reason(1200 + $qty_code);
741 $logger->warn("EDI: Unhandled quantity qty_code '$qty_code' ".
742 "for li $li_id. $qty_count items unprocessed");
746 my ($cancel_count, $fatal) =
747 $class->cancel_lids($e, $eg_reason, $qty_count, $lid_count, \@lids);
751 $lids_cancelled += $cancel_count;
753 # if ALL the items have the same cancel_reason, the LI gets it too
754 if ($qty_count == $lid_count) {
755 $li->cancel_reason($eg_reason->id);
756 $li->state("cancelled");
759 $li->edit_time('now');
760 unless ($e->update_acq_lineitem($li)) {
761 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
766 # in case the provider neglected to echo back the order count
767 $order_qty = $lid_count unless defined $order_qty;
769 # it may be necessary to change the logic here to look for lineitem
770 # order status / availability status instead of dispatch_qty and
771 # assume that dispatch_qty simply equals the number of unaccounted-for copies
772 if (defined $dispatch_qty) {
773 # provider is telling us how may copies were delivered
775 # number of copies neither cancelled or delivered
776 my $remaining_lids = $order_qty - ($dispatch_qty + $lids_cancelled);
778 if ($remaining_lids > 0) {
780 # the vendor did not ship all items and failed to provide cancellation
781 # quantities for some or all of the items to be cancelled. When this
782 # happens, we cancel the remaining un-delivered copies using the
783 # lineitem order status to determine the cancel reason.
788 if ($stat = $li_hash->{order_status}) {
789 $logger->info("EDI: lineitem has order status $stat");
791 if ($stat eq '200') {
792 $reason_id = 1007; # not accepted
794 } elsif ($stat eq '400') {
795 $reason_id = 1283; # back-order
798 } elsif ($stat = $li_hash->{avail_status}) {
799 $logger->info("EDI: lineitem has availability status $stat");
803 # TODO: needs cancellation?
808 my $reason = $e->retrieve_acq_cancel_reason($reason_id);
810 my ($cancel_count, $fatal) =
811 $class->cancel_lids($e, $reason, $remaining_lids, $lid_count, \@lids);
814 $lids_cancelled += $cancel_count;
816 # All LIDs cancelled with same reason, apply
817 # the same cancel reason to the lineitem
818 if ($remaining_lids == $order_qty) {
819 $li->cancel_reason($reason->id);
820 $li->state("cancelled");
823 $li->edit_time('now');
824 unless ($e->update_acq_lineitem($li)) {
825 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
830 $logger->warn("EDI: vendor says we ordered $order_qty and cancelled ".
831 "$lids_cancelled, but only shipped $dispatch_qty");
836 # LI and LIDs updated, let's wrap this one up.
837 # this is a no-op if the xact has already been rolled back
840 $logger->info("EDI: LI $li_id -- $order_qty LIDs ordered; ".
841 "$lids_cancelled LIDs cancelled");
846 my ($class, $e, $reason, $count, $lid_count, $lid_ids) = @_;
848 my $cancel_count = 0;
850 foreach (1 .. $count) {
852 my $lid_id = shift @$lid_ids;
855 $logger->warn("EDI: Used up all $lid_count LIDs. ".
856 "Ignoring extra status '" . $reason->label . "'");
860 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
861 $lid->cancel_reason($reason->id);
863 # item is cancelled. Remove the fund debit.
864 unless ($U->is_true($reason->keep_debits)) {
866 if (my $debit_id = $lid->fund_debit) {
868 $lid->clear_fund_debit;
869 my $debit = $e->retrieve_acq_fund_debit($debit_id);
871 if ($U->is_true($debit->encumbrance)) {
872 $logger->info("EDI: deleting debit $debit_id for cancelled LID $lid_id");
874 unless ($e->delete_acq_fund_debit($debit)) {
875 $logger->error("EDI: unable to update fund_debit " . $e->die_event);
879 # do not delete a paid-for debit
880 $logger->warn("EDI: cannot delete invoiced debit $debit_id");
885 $e->update_acq_lineitem_detail($lid);
889 return ($cancel_count);
892 sub edi_date_to_iso {
893 my ($class, $date) = @_;
894 return undef unless $date and $date =~ /\d+/;
895 my ($iso, $m, $d) = $date =~ /^(\d{4})(\d{2})(\d{2})/g;
902 # Return hash with a key for every kludge that should apply for this
903 # msg_type (INVOIC,ORDRSP) and this vendor SAN.
905 my ($class, $msg_type, $vendor_san) = @_;
908 while (my ($kludge, $vendors) = each %{$VENDOR_KLUDGE_MAP->{$msg_type}}) {
909 push @kludges, $kludge if grep { $_ eq $vendor_san } @$vendors;
912 return map { $_ => 1 } @kludges;
915 sub invoice_lineitem_to_invoice_entry {
916 my ($li, $quantity, $price) = @_;
918 my $eg_inv_entry = Fieldmapper::acq::invoice_entry->new;
919 $eg_inv_entry->isnew(1);
920 $eg_inv_entry->inv_item_count($quantity);
922 # amount staff agree to pay for
923 $eg_inv_entry->phys_item_count($quantity);
925 # XXX Validate by making sure the LI is on-order and belongs to
926 # the right provider and ordering agency and all that.
927 $eg_inv_entry->lineitem($li->id);
929 # XXX Do we actually need to link to PO directly here?
930 $eg_inv_entry->purchase_order($li->purchase_order);
932 # This is the total price for all units billed, not per-unit.
933 $eg_inv_entry->cost_billed($price);
935 # amount staff agree to pay
936 $eg_inv_entry->amount_paid($price);
938 # The EDIReader class does detect certain per-lineitem
939 # taxes, but we'll ignore them for now, as the only sample
940 # invoices I've yet seen containing them also had a final
941 # cumulative tax at the end.
943 return $eg_inv_entry;
946 # Return an arrayref containing acqie objects, an another of unknown lineitem
947 # references from the electronic invoice.
948 # @param $message An acqedim object
949 # @param $invoice_lineitems An arrayref from part of EDIReader output
950 # NOTE: This sub can have side-effects on $message.
951 sub process_invoice_lineitems {
952 my ($e, $msg_kludges, $log_prefix, $message, $invoice_lineitems) = @_;
954 my (@entries, @unknowns);
956 foreach my $lineitem (@$invoice_lineitems) {
957 if (!$lineitem->{id}) {
958 $logger->warn($log_prefix . "no lineitem ID");
962 my ($quant) = grep {$_->{code} eq '47'} @{$lineitem->{quantities}};
963 my $quantity = ($quant) ? $quant->{quantity} : 0;
966 $logger->warn($log_prefix . "no invoice quantity " .
967 "specified for invoice LI $lineitem->{id}");
971 # NOTE: if needed, we also have $lineitem->{net_unit_price}
972 # and $lineitem->{gross_unit_price}
973 my $price = $lineitem->{amount_billed};
975 # XXX Should we set acqie.billed_per_item=t in this case
976 # instead? Not sure whether that actually works everywhere
978 $price *= $quantity if $msg_kludges->{amount_billed_is_per_unit};
980 my $li = $e->retrieve_acq_lineitem($lineitem->{id});
983 # If the top-level PO value is unset, get it from the first LI
984 $message->purchase_order($li->purchase_order)
985 unless $message->purchase_order;
987 push @entries, invoice_lineitem_to_invoice_entry(
988 $li, $quantity, $price
991 push @unknowns, $lineitem->{id};
995 return \@entries, \@unknowns;
998 # create_acq_invoice_from_edi() does what it sounds like it does for INVOIC
999 # messages. For similar operation on ORDRSP messages, see the guts of
1001 # Return boolean success indicator.
1002 sub create_acq_invoice_from_edi {
1003 my ($class, $msg_data, $provider, $message) = @_;
1004 # $msg_data is O::U::EDIReader hash
1005 # $provider is only a pkey
1006 # $message is Fieldmapper::acq::edi_message
1008 my $e = new_editor();
1010 my $log_prefix = "create_acq_invoice_from_edi(..., <acq.edi_message #" .
1011 $message->id . ">): ";
1014 if ($msg_data->{vendor_san}) {
1015 %msg_kludges = $class->get_kludges('INVOIC', $msg_data->{vendor_san});
1017 $logger->warn($log_prefix . "no vendor_san field!");
1020 my $eg_inv = Fieldmapper::acq::invoice->new;
1023 # Some troubleshooting aids. Yeah we should have made appropriate links
1024 # for this in the schema, but this is better than nothing. Probably
1025 # *don't* try to i18n this.
1026 $eg_inv->note("Generated from acq.edi_message #" . $message->id . ".");
1030 " Vendor kludges: " . join(", ", keys(%msg_kludges)) . "."
1034 $eg_inv->provider($provider);
1035 $eg_inv->shipper($provider); # XXX Do we really have a meaningful way to
1036 # distinguish provider and shipper?
1037 $eg_inv->recv_method("EDI");
1040 $class->edi_date_to_iso($msg_data->{invoice_date}));
1043 $class->process_message_buyer($e, $msg_data, $message, $log_prefix, $eg_inv);
1045 if (!$eg_inv->receiver) {
1047 sprintf("unable to determine buyer (org unit) in invoice; ".
1048 "buyer_san=%s; buyer_acct=%s",
1049 ($msg_data->{buyer_san} || ''),
1050 ($msg_data->{buyer_acct} || '')
1055 $eg_inv->inv_ident($msg_data->{invoice_ident});
1057 if (!$eg_inv->inv_ident) {
1058 die($log_prefix . "no invoice ID # in INVOIC message; " . shift);
1061 $message->purchase_order($msg_data->{purchase_order});
1063 # Invoice lineitems should generally link to Evergreen lineitems
1064 # (with acq.invoice_entry rows), except when they don't refer to any
1065 # Evergreen lineitems by their known number. In that case, they're
1066 # probably things ordered not through the ILS. We don't have an
1067 # appropriate table for storing that kind of information right now,
1068 # so we skip those. No, we don't have enough information to create
1069 # Evergreen lineitems on the fly and create acqie rows linking to
1071 my ($eg_inv_entries, $unknowns) = process_invoice_lineitems(
1072 $e, \%msg_kludges, $log_prefix, $message, $msg_data->{lineitems}
1077 $log_prefix . sprintf(
1078 "skipped %d unknown lineitem reference(s) from EDI invoice: %s",
1080 join("; ", map { "'$_'" } @$unknowns)
1085 my %charge_type_map = (
1086 'TX' => ['TAX', 'Tax from electronic invoice'],
1087 'CA' => ['PRO', 'Cataloging services'],
1088 'DL' => ['SHP', 'Delivery'],
1089 'GST' => ['TAX', 'Goods and services tax']
1090 ); # XXX i18n, somehow
1092 my $eg_inv_items = [];
1094 for my $charge (@{$msg_data->{misc_charges}}, @{$msg_data->{taxes}}) {
1095 my $eg_inv_item = Fieldmapper::acq::invoice_item->new;
1096 $eg_inv_item->isnew(1);
1098 my $amount = $charge->{amount};
1101 $logger->warn($log_prefix . "charge with no amount");
1105 my $map = $charge_type_map{$charge->{type}};
1108 $map = ['PRO', 'Misc / unspecified'];
1109 $eg_inv_item->note($charge->{type});
1112 $eg_inv_item->inv_item_type($$map[0]);
1113 $eg_inv_item->title($$map[1]); # title is user-visible; note isn't.
1114 $eg_inv_item->cost_billed($amount);
1115 $eg_inv_item->amount_paid($amount);
1117 push @$eg_inv_items, $eg_inv_item;
1120 $logger->info($log_prefix .
1121 sprintf("creating invoice with %d entries and %d items.",
1122 scalar(@$eg_inv_entries), scalar(@$eg_inv_items)));
1126 # save changes to acq.edi_message row
1127 if (not $e->update_acq_edi_message($message)) {
1128 die($log_prefix . "couldn't update edi_message " . $message->id);
1131 my $result = OpenILS::Application::Acq::Invoice::build_invoice_impl(
1132 $e, $eg_inv, $eg_inv_entries, $eg_inv_items, 0 # don't commit yet
1135 if ($U->event_code($result)) {
1136 die($log_prefix. "build_invoice_impl() failed: " . $result->{textcode});