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 => {ilike => $remote_file},
139 status => {'in' => [qw/ processed /]},
141 { join => {"acqedi" => {}}, limit => 1 }
146 my $msg = "EDI: test for already-retrieved files yielded " .
147 "event " . $e->event->{textcode};
150 return $e->die_event;
154 $logger->debug("EDI: $remote_file already retrieved. Skipping");
155 warn "EDI: $remote_file already retrieved. Skipping";
160 if ($max and $count > $max) {
165 sprintf "%s of %s targets: %s",
166 $count, scalar(@ok_files), $description
168 printf("%d of %d targets: %s\n", $count, scalar(@ok_files), $description);
170 push @return, "test_$count";
174 my $io = IO::Scalar->new(\$content);
177 $server->get({remote_file => $remote_file, local_file => $io})
179 $logger->error("(S)FTP get($description) failed");
183 my $incoming = __PACKAGE__->process_retrieval(
184 $content, $remote_file, $server, $account->id
187 push @return, @$incoming;
194 # procses_retrieval() returns a reference to a list of acq.edi_message IDs
195 sub process_retrieval {
196 my ($class, $content, $filename, $server, $account_or_id) = @_;
200 my $account = __PACKAGE__->record_activity($account_or_id, $e);
202 # a single EDI blob can contain multiple messages
203 # create one edi_message per included message
205 my $messages = OpenILS::Utils::EDIReader->new->read($content);
208 for my $msg_hash (@$messages) {
210 my $incoming = Fieldmapper::acq::edi_message->new;
212 $incoming->remote_file($filename);
213 $incoming->account($account->id);
214 $incoming->edi($content);
215 $incoming->message_type($msg_hash->{message_type});
216 $incoming->jedi(OpenSRF::Utils::JSON->perl2JSON($msg_hash)); # jedi-2.0
217 $incoming->status('translated');
218 $incoming->translate_time('NOW');
220 if ($msg_hash->{purchase_order}) {
221 # Some vendors just put their name where there ought to be a number,
222 # and others put alphanumeric strings that mean nothing to us, so
223 # we sure won't match a PO in the system this way. We can pick
224 # up PO number later from the lineitems themselves if necessary.
226 if ($msg_hash->{purchase_order} !~ /^\d+$/) {
227 $logger->warn("EDI: PO identifier is non-numeric. Continuing.");
228 # No "next" here; we'll process this and just not link to acqpo.
230 $logger->info("EDI: processing message for PO " .
231 $msg_hash->{purchase_order});
232 $incoming->purchase_order($msg_hash->{purchase_order});
233 unless ($e->retrieve_acq_purchase_order(
234 $incoming->purchase_order)) {
235 $logger->warn("EDI: received order response for " .
236 "nonexistent PO. Skipping...");
243 unless($e->create_acq_edi_message($incoming)) {
244 $logger->error("EDI: unable to create edi_message " . $e->die_event);
247 # refresh to pickup create_date, etc.
248 $incoming = $e->retrieve_acq_edi_message($incoming->id);
251 # since there's a fair chance of unhandled problems
252 # cropping up, particularly with new vendors, wrap w/ eval.
253 eval { $class->process_parsed_msg($account, $incoming, $msg_hash) };
256 $incoming = $e->retrieve_acq_edi_message($incoming->id);
259 $incoming->status('proc_error');
260 $incoming->error_time('now');
261 $incoming->error($@);
263 $incoming->status('processed');
265 $e->update_acq_edi_message($incoming);
268 push(@return, $incoming->id);
275 # $account is a Fieldmapper object for acq.edi_account row
276 # $message_ids is an arrayref with acq.edi_message.id values
277 # $e is optional editor object
279 my ($class, $account, $message_ids, $e) = @_; # $e is a working editor
281 return unless $account and @$message_ids;
285 my @messageset = map {$e->retrieve_acq_edi_message($_)} @$message_ids;
287 my $m_count = scalar(@messageset);
288 if (@$message_ids != $m_count) {
289 $logger->warn(scalar(@$message_ids) - $m_count . " bad IDs passed to send_core (ignored)");
292 my $log_str = sprintf "EDI send to edi_account %s (%s)", $account->id, $account->host;
293 $logger->info("$log_str: $m_count message(s)");
294 return unless $m_count;
298 unless ($server = __PACKAGE__->remote_account($account, 1)) { # assignment
299 $logger->error("Failed remote account connection for $log_str");
303 foreach (@messageset) {
304 $_ or next; # we already warned about bum ids
307 # We already told $logger; this is to update object below
308 $error = "Server error: Failed remote account connection ".
310 } elsif (! $_->edi) {
312 "Message (id " . $_->id. ") for $log_str has no EDI content"
314 $error = "EDI empty!";
316 $res = $server->put({
317 remote_path => $account->path, content => $_->edi,
321 # This is the successful case!
322 $_->remote_file($res);
323 $_->status('complete');
324 $_->process_time('NOW');
326 # For outbound files, sending is the end of processing on
329 $logger->info("Sent message (id " . $_->id. ") via $log_str");
332 "(S)FTP put to $log_str FAILED: " .
333 ($server->error || 'UNKOWNN')
335 $error = "put FAILED: " . ($server->error || 'UNKOWNN');
340 $_->error_time('NOW');
343 $logger->info("Calling update_acq_edi_message");
346 unless ($e->update_acq_edi_message($_)) {
348 "EDI send_core update_acq_edi_message failed " .
349 "for message object: " . Dumper($_)
352 OpenILS::Application::Acq::EDI::Translator->debug_file(
354 '/tmp/update_acq_edi_message.FAIL'
356 OpenILS::Application::Acq::EDI::Translator->debug_file(
357 Dumper($_->to_bare_hash),
358 '/tmp/update_acq_edi_message.FAIL.to_bare_hash'
362 # There's always an update, even if we failed.
364 __PACKAGE__->record_activity($account, $e);
369 # attempt_translation does not touch the DB, just the object.
370 sub attempt_translation {
371 my ($class, $edi_message, $to_edi) = @_;
373 my $ret = $to_edi ? translator->json2edi($edi_message->jedi) :
374 translator->edi2json($edi_message->edi);
376 if (not $ret or (! ref($ret)) or $ret->is_fault) {
377 # RPC::XML::fault on failure
379 $edi_message->status('trans_error');
380 $edi_message->error_time('NOW');
381 my $pre = "EDI Translator " .
382 ($to_edi ? 'json2edi' : 'edi2json') . " failed";
384 my $message = ref($ret) ?
385 ("$pre, Error " . $ret->code . ": " .
386 __PACKAGE__->nice_string($ret->string)) :
387 ("$pre: " . __PACKAGE__->nice_string($ret)) ;
389 $edi_message->error($message);
390 $logger->error($message);
394 $edi_message->status('translated');
395 $edi_message->translate_time('NOW');
398 $edi_message->edi($ret->value); # translator returns an object
400 $edi_message->jedi($ret->value); # translator returns an object
406 sub retrieve_vendors {
407 my ($self, $e, $vendor_id, $last_activity) = @_; # $e is a working editor
411 my $criteria = {'+acqpro' => {active => 't'}};
412 $criteria->{'+acqpro'}->{id} = $vendor_id if $vendor_id;
413 return $e->search_acq_edi_account([
418 acqedi => ['provider']
424 # This is the SRF-exposed call, so it does checkauth
427 my ($self, $conn, $auth, $vendor_id, $last_activity, $max) = @_;
429 my $e = new_editor(authtoken=>$auth);
430 unless ($e and $e->checkauth()) {
431 $logger->warn("checkauth failed for authtoken '$auth'");
434 # return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency); # add permission here ?
436 my $set = __PACKAGE__->retrieve_vendors($e, $vendor_id, $last_activity) or return $e->die_event;
437 return __PACKAGE__->retrieve_core($e, $set, $max);
441 # field_map takes the hashref of vendor data with fields from acq.edi_account and
442 # maps them to the argument style needed for RemoteAccount. It also extrapolates
443 # data from the remote_host string for type and port, when available.
447 my $vendor = shift or return;
448 my $no_override = @_ ? shift : 0;
450 $verbose and $logger->warn("vendor: " . Dumper($vendor));
451 foreach (keys %map) {
452 $args{$map{$_}} = $vendor->$_ if defined $vendor->$_;
454 unless ($no_override) {
455 $args{remote_path} = $vendor->in_dir; # override "path" with "in_dir"
457 my $host = $args{remote_host} || '';
458 ($host =~ s/^(S?FTP)://i and $args{type} = uc($1)) or
459 ($host =~ s/^(SSH|SCP)://i and $args{type} = 'SCP' ) ;
460 $host =~ s/:(\d+)$// and $args{port} = $1;
461 ($args{remote_host} = $host) =~ s#/+##;
462 $verbose and $logger->warn("field_map: " . Dumper(\%args));
467 # The point of remote_account is to get the RemoteAccount object with args from the DB
470 my ($self, $vendor, $outbound, $e) = @_;
472 unless (ref($vendor)) { # It's not a hashref/object.
473 $vendor or return; # If in fact it's nothing: abort!
474 # else it's a vendor_id string, so get the full vendor data
476 my $set_of_one = $self->retrieve_vendors($e, $vendor) or return;
477 $vendor = shift @$set_of_one;
480 return OpenILS::Utils::RemoteAccount->new(
481 $self->field_map($vendor, $outbound)
485 # takes account ID or account Fieldmapper object
487 sub record_activity {
488 my ($class, $account_or_id, $e) = @_;
489 $account_or_id or return;
491 my $account = ref($account_or_id) ? $account_or_id : $e->retrieve_acq_edi_account($account_or_id);
492 $logger->info("EDI record_activity calling update_acq_edi_account");
493 $account->last_activity('NOW') or return;
495 $e->update_acq_edi_account($account) or $logger->warn("EDI: in record_activity, update_acq_edi_account FAILED");
502 my $string = shift or return '';
504 my $head = @_ ? shift : 100;
505 my $tail = @_ ? shift : 25;
506 (length($string) < $head + $tail) and return $string;
507 my $h = substr($string,0,$head);
508 my $t = substr($string, -1*$tail);
512 # return substr($string,0,$head) . "... " . substr($string, -1*$tail);
515 # process_message_buyer() is used in processing both INVOIC
516 # messages as well as ORDRSP ones. As such, the $eg_inv parameter is
518 sub process_message_buyer {
519 my ($class, $e, $msg_hash, $message, $log_prefix, $eg_inv) = @_;
521 # some vendors encode the account number as the SAN.
522 # starting with the san value, then the account value,
523 # treat each as a san, then an acct number until the first success
524 for my $buyer ( ($msg_hash->{buyer_san}, $msg_hash->{buyer_acct}) ) {
527 # some vendors encode the SAN as "$SAN $vendcode"
529 ($buyer, $vendcode) = $buyer =~ /(\S+)\s*(\S+)?$/;
531 my $addr = $e->search_actor_org_address(
532 {valid => "t", san => $buyer})->[0];
536 $eg_inv->receiver($addr->org_unit) if $eg_inv;
538 my $orig_acct = $e->retrieve_acq_edi_account($message->account);
540 if (defined($vendcode) and ($orig_acct->vendcode ne $vendcode)) {
541 # The vendcode can give us the opportunity to change the
542 # acq.edi_account with which our acq.edi_message is associated
543 # in case it's wrong.
545 my $other_accounts = $e->search_acq_edi_account(
547 vendcode => $vendcode,
548 host => $orig_acct->host,
549 username => $orig_acct->username,
550 password => $orig_acct->password,
551 in_dir => $orig_acct->in_dir
555 if (@$other_accounts) {
556 # We can update this object because the caller saves
557 # it with cstore later.
558 $message->account($other_accounts->[0]->id);
561 $log_prefix . sprintf(
562 "changing edi_account from %d to %d based on " .
564 $orig_acct->id, $message->account, $vendcode
574 my $acct = $e->search_acq_edi_account({vendacct => $buyer})->[0];
577 $eg_inv->receiver($acct->owner);
584 # parts of this process can fail without the entire
585 # thing failing. If a catastrophic error occurs,
586 # it will occur via die.
587 sub process_parsed_msg {
588 my ($class, $account, $incoming, $msg_hash) = @_;
591 if ($incoming->message_type eq 'INVOIC') {
592 return $class->create_acq_invoice_from_edi(
593 $msg_hash, $account->provider, $incoming);
598 # First do this for the whole message...
599 $class->process_message_buyer(
600 new_editor, $msg_hash, $incoming, "ORDRSP processing"
603 # ... now do this stuff per-lineitem.
604 for my $li_hash (@{$msg_hash->{lineitems}}) {
605 my $e = new_editor(xact => 1);
607 my $li_id = $li_hash->{id};
608 my $li = $e->retrieve_acq_lineitem($li_id);
611 $logger->error("EDI: request for invalid lineitem ID '$li_id'");
616 $li->expected_recv_time(
617 $class->edi_date_to_iso($li_hash->{expected_date}));
619 $li->estimated_unit_price($li_hash->{unit_price});
621 if (not $incoming->purchase_order) {
622 # PO should come from the EDI message, but if not...
624 # fetch the latest copy
625 $incoming = $e->retrieve_acq_edi_message($incoming->id);
626 $incoming->purchase_order($li->purchase_order);
628 unless($e->update_acq_edi_message($incoming)) {
629 $logger->error("EDI: unable to update edi_message " . $e->die_event);
634 my $lids = $e->json_query({
635 select => {acqlid => ['id']},
637 where => {lineitem => $li->id}
640 my @lids = map { $_->{id} } @$lids;
641 my $lid_count = scalar(@lids);
642 my $lids_covered = 0;
643 my $lids_cancelled = 0;
647 for my $qty (@{$li_hash->{quantities}}) {
649 my $qty_count = $qty->{quantity};
650 my $qty_code = $qty->{code};
652 next unless defined $qty_count;
655 $logger->warn("EDI: Response for LI $li_id specifies quantity ".
656 "$qty_count with no 6063 code! Contact vendor to resolve.");
660 $logger->info("EDI: LI $li_id processing quantity count=$qty_count / code=$qty_code");
662 if ($qty_code eq '21') { # "ordered quantity"
663 $order_qty = $qty_count;
664 $logger->info("EDI: LI $li_id -- vendor confirms $qty_count ordered");
665 $logger->warn("EDI: LI $li_id -- order count $qty_count ".
666 "does not match LID count $lid_count") unless $qty_count == $lid_count;
670 $lids_covered += $qty_count;
672 if ($qty_code eq '12') {
673 $dispatch_qty = $qty_count;
674 $logger->info("EDI: LI $li_id -- vendor dispatched $qty_count");
677 } elsif ($qty_code eq '57') {
678 $logger->info("EDI: LI $li_id -- $qty_count in transit");
681 # 84: urgent delivery
682 # 118: quantity manifested
685 # -------------------------------------------------------------------------
686 # All of the remaining quantity types require that we apply a cancel_reason
687 # DB populated w/ 6063 keys in 1200's
689 my $eg_reason = $e->retrieve_acq_cancel_reason(1200 + $qty_code);
692 $logger->warn("EDI: Unhandled quantity qty_code '$qty_code' ".
693 "for li $li_id. $qty_count items unprocessed");
697 my ($cancel_count, $fatal) =
698 $class->cancel_lids($e, $eg_reason, $qty_count, $lid_count, \@lids);
702 $lids_cancelled += $cancel_count;
704 # if ALL the items have the same cancel_reason, the LI gets it too
705 if ($qty_count == $lid_count) {
706 $li->cancel_reason($eg_reason->id);
707 $li->state("cancelled");
710 $li->edit_time('now');
711 unless ($e->update_acq_lineitem($li)) {
712 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
717 # in case the provider neglected to echo back the order count
718 $order_qty = $lid_count unless defined $order_qty;
720 # it may be necessary to change the logic here to look for lineitem
721 # order status / availability status instead of dispatch_qty and
722 # assume that dispatch_qty simply equals the number of unaccounted-for copies
723 if (defined $dispatch_qty) {
724 # provider is telling us how may copies were delivered
726 # number of copies neither cancelled or delivered
727 my $remaining_lids = $order_qty - ($dispatch_qty + $lids_cancelled);
729 if ($remaining_lids > 0) {
731 # the vendor did not ship all items and failed to provide cancellation
732 # quantities for some or all of the items to be cancelled. When this
733 # happens, we cancel the remaining un-delivered copies using the
734 # lineitem order status to determine the cancel reason.
739 if ($stat = $li_hash->{order_status}) {
740 $logger->info("EDI: lineitem has order status $stat");
742 if ($stat eq '200') {
743 $reason_id = 1007; # not accepted
745 } elsif ($stat eq '400') {
746 $reason_id = 1283; # back-order
749 } elsif ($stat = $li_hash->{avail_status}) {
750 $logger->info("EDI: lineitem has availability status $stat");
754 # TODO: needs cancellation?
759 my $reason = $e->retrieve_acq_cancel_reason($reason_id);
761 my ($cancel_count, $fatal) =
762 $class->cancel_lids($e, $reason, $remaining_lids, $lid_count, \@lids);
765 $lids_cancelled += $cancel_count;
767 # All LIDs cancelled with same reason, apply
768 # the same cancel reason to the lineitem
769 if ($remaining_lids == $order_qty) {
770 $li->cancel_reason($reason->id);
771 $li->state("cancelled");
774 $li->edit_time('now');
775 unless ($e->update_acq_lineitem($li)) {
776 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
781 $logger->warn("EDI: vendor says we ordered $order_qty and cancelled ".
782 "$lids_cancelled, but only shipped $dispatch_qty");
787 # LI and LIDs updated, let's wrap this one up.
788 # this is a no-op if the xact has already been rolled back
791 $logger->info("EDI: LI $li_id -- $order_qty LIDs ordered; ".
792 "$lids_cancelled LIDs cancelled");
797 my ($class, $e, $reason, $count, $lid_count, $lid_ids) = @_;
799 my $cancel_count = 0;
801 foreach (1 .. $count) {
803 my $lid_id = shift @$lid_ids;
806 $logger->warn("EDI: Used up all $lid_count LIDs. ".
807 "Ignoring extra status '" . $reason->label . "'");
811 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
812 $lid->cancel_reason($reason->id);
814 # item is cancelled. Remove the fund debit.
815 unless ($U->is_true($reason->keep_debits)) {
817 if (my $debit_id = $lid->fund_debit) {
819 $lid->clear_fund_debit;
820 my $debit = $e->retrieve_acq_fund_debit($debit_id);
822 if ($U->is_true($debit->encumbrance)) {
823 $logger->info("EDI: deleting debit $debit_id for cancelled LID $lid_id");
825 unless ($e->delete_acq_fund_debit($debit)) {
826 $logger->error("EDI: unable to update fund_debit " . $e->die_event);
830 # do not delete a paid-for debit
831 $logger->warn("EDI: cannot delete invoiced debit $debit_id");
836 $e->update_acq_lineitem_detail($lid);
840 return ($cancel_count);
843 sub edi_date_to_iso {
844 my ($class, $date) = @_;
845 return undef unless $date and $date =~ /\d+/;
846 my ($iso, $m, $d) = $date =~ /^(\d{4})(\d{2})(\d{2})/g;
853 # Return hash with a key for every kludge that should apply for this
854 # msg_type (INVOIC,ORDRSP) and this vendor SAN.
856 my ($class, $msg_type, $vendor_san) = @_;
859 while (my ($kludge, $vendors) = each %{$VENDOR_KLUDGE_MAP->{$msg_type}}) {
860 push @kludges, $kludge if grep { $_ eq $vendor_san } @$vendors;
863 return map { $_ => 1 } @kludges;
866 sub invoice_lineitem_to_invoice_entry {
867 my ($li, $quantity, $price) = @_;
869 my $eg_inv_entry = Fieldmapper::acq::invoice_entry->new;
870 $eg_inv_entry->isnew(1);
871 $eg_inv_entry->inv_item_count($quantity);
873 # amount staff agree to pay for
874 $eg_inv_entry->phys_item_count($quantity);
876 # XXX Validate by making sure the LI is on-order and belongs to
877 # the right provider and ordering agency and all that.
878 $eg_inv_entry->lineitem($li->id);
880 # XXX Do we actually need to link to PO directly here?
881 $eg_inv_entry->purchase_order($li->purchase_order);
883 # This is the total price for all units billed, not per-unit.
884 $eg_inv_entry->cost_billed($price);
886 # amount staff agree to pay
887 $eg_inv_entry->amount_paid($price);
889 # The EDIReader class does detect certain per-lineitem
890 # taxes, but we'll ignore them for now, as the only sample
891 # invoices I've yet seen containing them also had a final
892 # cumulative tax at the end.
894 return $eg_inv_entry;
897 # Return an arrayref containing acqie objects, an another of unknown lineitem
898 # references from the electronic invoice.
899 # @param $message An acqedim object
900 # @param $invoice_lineitems An arrayref from part of EDIReader output
901 sub process_invoice_lineitems {
902 my ($e, $msg_kludges, $log_prefix, $message, $invoice_lineitems) = @_;
904 my (@entries, @unknowns);
906 foreach my $lineitem (@$invoice_lineitems) {
907 if (!$lineitem->{id}) {
908 $logger->warn($log_prefix . "no lineitem ID");
912 my ($quant) = grep {$_->{code} eq '47'} @{$lineitem->{quantities}};
913 my $quantity = ($quant) ? $quant->{quantity} : 0;
916 $logger->warn($log_prefix . "no invoice quantity " .
917 "specified for invoice LI $lineitem->{id}");
921 # NOTE: if needed, we also have $lineitem->{net_unit_price}
922 # and $lineitem->{gross_unit_price}
923 my $price = $lineitem->{amount_billed};
925 # XXX Should we set acqie.billed_per_item=t in this case
926 # instead? Not sure whether that actually works everywhere
928 $price *= $quantity if $msg_kludges->{amount_billed_is_per_unit};
930 my $li = $e->retrieve_acq_lineitem($lineitem->{id});
933 # If the top-level PO value is unset, get it from the first LI
934 $message->purchase_order($li->purchase_order)
935 unless $message->purchase_order;
937 push @entries, invoice_lineitem_to_invoice_entry(
938 $li, $quantity, $price
941 push @unknowns, $lineitem->{id};
945 return \@entries, \@unknowns;
948 # create_acq_invoice_from_edi() does what it sounds like it does for INVOIC
949 # messages. For similar operation on ORDRSP messages, see the guts of
951 # Return boolean success indicator.
952 sub create_acq_invoice_from_edi {
953 my ($class, $msg_data, $provider, $message) = @_;
954 # $msg_data is O::U::EDIReader hash
955 # $provider is only a pkey
956 # $message is Fieldmapper::acq::edi_message
958 my $e = new_editor();
960 my $log_prefix = "create_acq_invoice_from_edi(..., <acq.edi_message #" .
961 $message->id . ">): ";
964 if ($msg_data->{vendor_san}) {
965 %msg_kludges = $class->get_kludges('INVOIC', $msg_data->{vendor_san});
967 $logger->warn($log_prefix . "no vendor_san field!");
970 my $eg_inv = Fieldmapper::acq::invoice->new;
973 # Some troubleshooting aids. Yeah we should have made appropriate links
974 # for this in the schema, but this is better than nothing. Probably
975 # *don't* try to i18n this.
976 $eg_inv->note("Generated from acq.edi_message #" . $message->id . ".");
980 " Vendor kludges: " . join(", ", keys(%msg_kludges)) . "."
984 $eg_inv->provider($provider);
985 $eg_inv->shipper($provider); # XXX Do we really have a meaningful way to
986 # distinguish provider and shipper?
987 $eg_inv->recv_method("EDI");
990 $class->edi_date_to_iso($msg_data->{invoice_date}));
993 $class->process_message_buyer($e, $msg_data, $message, $log_prefix, $eg_inv);
995 if (!$eg_inv->receiver) {
997 sprintf("unable to determine buyer (org unit) in invoice; ".
998 "buyer_san=%s; buyer_acct=%s",
999 ($msg_data->{buyer_san} || ''),
1000 ($msg_data->{buyer_acct} || '')
1005 $eg_inv->inv_ident($msg_data->{invoice_ident});
1007 if (!$eg_inv->inv_ident) {
1008 die($log_prefix . "no invoice ID # in INVOIC message; " . shift);
1011 $message->purchase_order($msg_data->{purchase_order});
1013 # Invoice lineitems should generally link to Evergreen lineitems
1014 # (with acq.invoice_entry rows), except when they don't refer to any
1015 # Evergreen lineitems by their known number. In that case, they're
1016 # probably things ordered not through the ILS. We don't have an
1017 # appropriate table for storing that kind of information right now,
1018 # so we skip those. No, we don't have enough information to create
1019 # Evergreen lineitems on the fly and create acqie rows linking to
1021 my ($eg_inv_entries, $unknowns) = process_invoice_lineitems(
1022 $e, \%msg_kludges, $log_prefix, $message, $msg_data->{lineitems}
1027 $log_prefix . sprintf(
1028 "skipped %d unknown lineitem reference(s) from EDI invoice: %s",
1030 join("; ", map { "'$_'" } @$unknowns)
1035 my %charge_type_map = (
1036 'TX' => ['TAX', 'Tax from electronic invoice'],
1037 'CA' => ['PRO', 'Cataloging services'],
1038 'DL' => ['SHP', 'Delivery'],
1039 'GST' => ['TAX', 'Goods and services tax']
1040 ); # XXX i18n, somehow
1042 my $eg_inv_items = [];
1044 for my $charge (@{$msg_data->{misc_charges}}, @{$msg_data->{taxes}}) {
1045 my $eg_inv_item = Fieldmapper::acq::invoice_item->new;
1046 $eg_inv_item->isnew(1);
1048 my $amount = $charge->{amount};
1051 $logger->warn($log_prefix . "charge with no amount");
1055 my $map = $charge_type_map{$charge->{type}};
1058 $map = ['PRO', 'Misc / unspecified'];
1059 $eg_inv_item->note($charge->{type});
1062 $eg_inv_item->inv_item_type($$map[0]);
1063 $eg_inv_item->title($$map[1]); # title is user-visible; note isn't.
1064 $eg_inv_item->cost_billed($amount);
1065 $eg_inv_item->amount_paid($amount);
1067 push @$eg_inv_items, $eg_inv_item;
1070 $logger->info($log_prefix .
1071 sprintf("creating invoice with %d entries and %d items.",
1072 scalar(@$eg_inv_entries), scalar(@$eg_inv_items)));
1076 # save changes to acq.edi_message row
1077 if (not $e->update_acq_edi_message($message)) {
1078 die($log_prefix . "couldn't update edi_message " . $message->id);
1081 my $result = OpenILS::Application::Acq::Invoice::build_invoice_impl(
1082 $e, $eg_inv, $eg_inv_entries, $eg_inv_items, 0 # don't commit yet
1085 if ($U->event_code($result)) {
1086 die($log_prefix. "build_invoice_impl() failed: " . $result->{textcode});