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 => $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 $logger->info("EDI: processing message for PO " . $msg_hash->{purchase_order});
222 $incoming->purchase_order($msg_hash->{purchase_order});
223 unless ($e->retrieve_acq_purchase_order($incoming->purchase_order)) {
224 $logger->warn("EDI: received order response for nonexistent PO. Skipping...");
230 unless($e->create_acq_edi_message($incoming)) {
231 $logger->error("EDI: unable to create edi_message " . $e->die_event);
234 # refresh to pickup create_date, etc.
235 $incoming = $e->retrieve_acq_edi_message($incoming->id);
238 # since there's a fair chance of unhandled problems
239 # cropping up, particularly with new vendors, wrap w/ eval.
240 eval { $class->process_parsed_msg($account, $incoming, $msg_hash) };
243 $incoming = $e->retrieve_acq_edi_message($incoming->id);
246 $incoming->status('proc_error');
247 $incoming->error_time('now');
248 $incoming->error($@);
250 $incoming->status('processed');
252 $e->update_acq_edi_message($incoming);
255 push(@return, $incoming->id);
262 # $account is a Fieldmapper object for acq.edi_account row
263 # $message_ids is an arrayref with acq.edi_message.id values
264 # $e is optional editor object
266 my ($class, $account, $message_ids, $e) = @_; # $e is a working editor
268 return unless $account and @$message_ids;
272 my @messageset = map {$e->retrieve_acq_edi_message($_)} @$message_ids;
274 my $m_count = scalar(@messageset);
275 if (@$message_ids != $m_count) {
276 $logger->warn(scalar(@$message_ids) - $m_count . " bad IDs passed to send_core (ignored)");
279 my $log_str = sprintf "EDI send to edi_account %s (%s)", $account->id, $account->host;
280 $logger->info("$log_str: $m_count message(s)");
281 return unless $m_count;
285 unless ($server = __PACKAGE__->remote_account($account, 1)) { # assignment
286 $logger->error("Failed remote account connection for $log_str");
290 foreach (@messageset) {
291 $_ or next; # we already warned about bum ids
294 # We already told $logger; this is to update object below
295 $error = "Server error: Failed remote account connection ".
297 } elsif (! $_->edi) {
299 "Message (id " . $_->id. ") for $log_str has no EDI content"
301 $error = "EDI empty!";
303 $res = $server->put({
304 remote_path => $account->path, content => $_->edi,
308 # This is the successful case!
309 $_->remote_file($res);
310 $_->status('complete');
311 $_->process_time('NOW');
313 # For outbound files, sending is the end of processing on
316 $logger->info("Sent message (id " . $_->id. ") via $log_str");
319 "(S)FTP put to $log_str FAILED: " .
320 ($server->error || 'UNKOWNN')
322 $error = "put FAILED: " . ($server->error || 'UNKOWNN');
327 $_->error_time('NOW');
330 $logger->info("Calling update_acq_edi_message");
333 unless ($e->update_acq_edi_message($_)) {
335 "EDI send_core update_acq_edi_message failed " .
336 "for message object: " . Dumper($_)
339 OpenILS::Application::Acq::EDI::Translator->debug_file(
341 '/tmp/update_acq_edi_message.FAIL'
343 OpenILS::Application::Acq::EDI::Translator->debug_file(
344 Dumper($_->to_bare_hash),
345 '/tmp/update_acq_edi_message.FAIL.to_bare_hash'
349 # There's always an update, even if we failed.
351 __PACKAGE__->record_activity($account, $e);
356 # attempt_translation does not touch the DB, just the object.
357 sub attempt_translation {
358 my ($class, $edi_message, $to_edi) = @_;
360 my $ret = $to_edi ? translator->json2edi($edi_message->jedi) :
361 translator->edi2json($edi_message->edi);
363 if (not $ret or (! ref($ret)) or $ret->is_fault) {
364 # RPC::XML::fault on failure
366 $edi_message->status('trans_error');
367 $edi_message->error_time('NOW');
368 my $pre = "EDI Translator " .
369 ($to_edi ? 'json2edi' : 'edi2json') . " failed";
371 my $message = ref($ret) ?
372 ("$pre, Error " . $ret->code . ": " .
373 __PACKAGE__->nice_string($ret->string)) :
374 ("$pre: " . __PACKAGE__->nice_string($ret)) ;
376 $edi_message->error($message);
377 $logger->error($message);
381 $edi_message->status('translated');
382 $edi_message->translate_time('NOW');
385 $edi_message->edi($ret->value); # translator returns an object
387 $edi_message->jedi($ret->value); # translator returns an object
393 sub retrieve_vendors {
394 my ($self, $e, $vendor_id, $last_activity) = @_; # $e is a working editor
398 my $criteria = {'+acqpro' => {active => 't'}};
399 $criteria->{'+acqpro'}->{id} = $vendor_id if $vendor_id;
400 return $e->search_acq_edi_account([
405 acqedi => ['provider']
411 # This is the SRF-exposed call, so it does checkauth
414 my ($self, $conn, $auth, $vendor_id, $last_activity, $max) = @_;
416 my $e = new_editor(authtoken=>$auth);
417 unless ($e and $e->checkauth()) {
418 $logger->warn("checkauth failed for authtoken '$auth'");
421 # return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency); # add permission here ?
423 my $set = __PACKAGE__->retrieve_vendors($e, $vendor_id, $last_activity) or return $e->die_event;
424 return __PACKAGE__->retrieve_core($e, $set, $max);
428 # field_map takes the hashref of vendor data with fields from acq.edi_account and
429 # maps them to the argument style needed for RemoteAccount. It also extrapolates
430 # data from the remote_host string for type and port, when available.
434 my $vendor = shift or return;
435 my $no_override = @_ ? shift : 0;
437 $verbose and $logger->warn("vendor: " . Dumper($vendor));
438 foreach (keys %map) {
439 $args{$map{$_}} = $vendor->$_ if defined $vendor->$_;
441 unless ($no_override) {
442 $args{remote_path} = $vendor->in_dir; # override "path" with "in_dir"
444 my $host = $args{remote_host} || '';
445 ($host =~ s/^(S?FTP)://i and $args{type} = uc($1)) or
446 ($host =~ s/^(SSH|SCP)://i and $args{type} = 'SCP' ) ;
447 $host =~ s/:(\d+)$// and $args{port} = $1;
448 ($args{remote_host} = $host) =~ s#/+##;
449 $verbose and $logger->warn("field_map: " . Dumper(\%args));
454 # The point of remote_account is to get the RemoteAccount object with args from the DB
457 my ($self, $vendor, $outbound, $e) = @_;
459 unless (ref($vendor)) { # It's not a hashref/object.
460 $vendor or return; # If in fact it's nothing: abort!
461 # else it's a vendor_id string, so get the full vendor data
463 my $set_of_one = $self->retrieve_vendors($e, $vendor) or return;
464 $vendor = shift @$set_of_one;
467 return OpenILS::Utils::RemoteAccount->new(
468 $self->field_map($vendor, $outbound)
472 # takes account ID or account Fieldmapper object
474 sub record_activity {
475 my ($class, $account_or_id, $e) = @_;
476 $account_or_id or return;
478 my $account = ref($account_or_id) ? $account_or_id : $e->retrieve_acq_edi_account($account_or_id);
479 $logger->info("EDI record_activity calling update_acq_edi_account");
480 $account->last_activity('NOW') or return;
482 $e->update_acq_edi_account($account) or $logger->warn("EDI: in record_activity, update_acq_edi_account FAILED");
489 my $string = shift or return '';
491 my $head = @_ ? shift : 100;
492 my $tail = @_ ? shift : 25;
493 (length($string) < $head + $tail) and return $string;
494 my $h = substr($string,0,$head);
495 my $t = substr($string, -1*$tail);
499 # return substr($string,0,$head) . "... " . substr($string, -1*$tail);
502 # process_message_buyer() is used in processing both INVOIC
503 # messages as well as ORDRSP ones. As such, the $eg_inv parameter is
505 sub process_message_buyer {
506 my ($class, $e, $msg_hash, $message, $log_prefix, $eg_inv) = @_;
508 # some vendors encode the account number as the SAN.
509 # starting with the san value, then the account value,
510 # treat each as a san, then an acct number until the first success
511 for my $buyer ( ($msg_hash->{buyer_san}, $msg_hash->{buyer_acct}) ) {
514 # some vendors encode the SAN as "$SAN $vendcode"
516 ($buyer, $vendcode) = $buyer =~ /(\S+)\s*(\S+)?$/;
518 my $addr = $e->search_actor_org_address(
519 {valid => "t", san => $buyer})->[0];
523 $eg_inv->receiver($addr->org_unit) if $eg_inv;
525 my $orig_acct = $e->retrieve_acq_edi_account($message->account);
527 if (defined($vendcode) and ($orig_acct->vendcode ne $vendcode)) {
528 # The vendcode can give us the opportunity to change the
529 # acq.edi_account with which our acq.edi_message is associated
530 # in case it's wrong.
532 my $other_accounts = $e->search_acq_edi_account(
534 vendcode => $vendcode,
535 host => $orig_acct->host,
536 username => $orig_acct->username,
537 password => $orig_acct->password,
538 in_dir => $orig_acct->in_dir
542 if (@$other_accounts) {
543 # We can update this object because the caller saves
544 # it with cstore later.
545 $message->account($other_accounts->[0]->id);
548 $log_prefix . sprintf(
549 "changing edi_account from %d to %d based on " .
551 $orig_acct->id, $message->account, $vendcode
561 my $acct = $e->search_acq_edi_account({vendacct => $buyer})->[0];
564 $eg_inv->receiver($acct->owner);
571 # parts of this process can fail without the entire
572 # thing failing. If a catastrophic error occurs,
573 # it will occur via die.
574 sub process_parsed_msg {
575 my ($class, $account, $incoming, $msg_hash) = @_;
578 if ($incoming->message_type eq 'INVOIC') {
579 return $class->create_acq_invoice_from_edi(
580 $msg_hash, $account->provider, $incoming);
585 # First do this for the whole message...
586 $class->process_message_buyer(
587 new_editor, $msg_hash, $incoming, "ORDRSP processing"
590 # ... now do this stuff per-lineitem.
591 for my $li_hash (@{$msg_hash->{lineitems}}) {
592 my $e = new_editor(xact => 1);
594 my $li_id = $li_hash->{id};
595 my $li = $e->retrieve_acq_lineitem($li_id);
598 $logger->error("EDI: request for invalid lineitem ID '$li_id'");
603 $li->expected_recv_time(
604 $class->edi_date_to_iso($li_hash->{expected_date}));
606 $li->estimated_unit_price($li_hash->{unit_price});
608 if (not $incoming->purchase_order) {
609 # PO should come from the EDI message, but if not...
611 # fetch the latest copy
612 $incoming = $e->retrieve_acq_edi_message($incoming->id);
613 $incoming->purchase_order($li->purchase_order);
615 unless($e->update_acq_edi_message($incoming)) {
616 $logger->error("EDI: unable to update edi_message " . $e->die_event);
621 my $lids = $e->json_query({
622 select => {acqlid => ['id']},
624 where => {lineitem => $li->id}
627 my @lids = map { $_->{id} } @$lids;
628 my $lid_count = scalar(@lids);
629 my $lids_covered = 0;
630 my $lids_cancelled = 0;
634 for my $qty (@{$li_hash->{quantities}}) {
636 my $qty_count = $qty->{quantity};
637 my $qty_code = $qty->{code};
639 next unless defined $qty_count;
642 $logger->warn("EDI: Response for LI $li_id specifies quantity ".
643 "$qty_count with no 6063 code! Contact vendor to resolve.");
647 $logger->info("EDI: LI $li_id processing quantity count=$qty_count / code=$qty_code");
649 if ($qty_code eq '21') { # "ordered quantity"
650 $order_qty = $qty_count;
651 $logger->info("EDI: LI $li_id -- vendor confirms $qty_count ordered");
652 $logger->warn("EDI: LI $li_id -- order count $qty_count ".
653 "does not match LID count $lid_count") unless $qty_count == $lid_count;
657 $lids_covered += $qty_count;
659 if ($qty_code eq '12') {
660 $dispatch_qty = $qty_count;
661 $logger->info("EDI: LI $li_id -- vendor dispatched $qty_count");
664 } elsif ($qty_code eq '57') {
665 $logger->info("EDI: LI $li_id -- $qty_count in transit");
668 # 84: urgent delivery
669 # 118: quantity manifested
672 # -------------------------------------------------------------------------
673 # All of the remaining quantity types require that we apply a cancel_reason
674 # DB populated w/ 6063 keys in 1200's
676 my $eg_reason = $e->retrieve_acq_cancel_reason(1200 + $qty_code);
679 $logger->warn("EDI: Unhandled quantity qty_code '$qty_code' ".
680 "for li $li_id. $qty_count items unprocessed");
684 my ($cancel_count, $fatal) =
685 $class->cancel_lids($e, $eg_reason, $qty_count, $lid_count, \@lids);
689 $lids_cancelled += $cancel_count;
691 # if ALL the items have the same cancel_reason, the LI gets it too
692 if ($qty_count == $lid_count) {
693 $li->cancel_reason($eg_reason->id);
694 $li->state("cancelled");
697 $li->edit_time('now');
698 unless ($e->update_acq_lineitem($li)) {
699 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
704 # in case the provider neglected to echo back the order count
705 $order_qty = $lid_count unless defined $order_qty;
707 # it may be necessary to change the logic here to look for lineitem
708 # order status / availability status instead of dispatch_qty and
709 # assume that dispatch_qty simply equals the number of unaccounted-for copies
710 if (defined $dispatch_qty) {
711 # provider is telling us how may copies were delivered
713 # number of copies neither cancelled or delivered
714 my $remaining_lids = $order_qty - ($dispatch_qty + $lids_cancelled);
716 if ($remaining_lids > 0) {
718 # the vendor did not ship all items and failed to provide cancellation
719 # quantities for some or all of the items to be cancelled. When this
720 # happens, we cancel the remaining un-delivered copies using the
721 # lineitem order status to determine the cancel reason.
726 if ($stat = $li_hash->{order_status}) {
727 $logger->info("EDI: lineitem has order status $stat");
729 if ($stat eq '200') {
730 $reason_id = 1007; # not accepted
732 } elsif ($stat eq '400') {
733 $reason_id = 1283; # back-order
736 } elsif ($stat = $li_hash->{avail_status}) {
737 $logger->info("EDI: lineitem has availability status $stat");
741 # TODO: needs cancellation?
746 my $reason = $e->retrieve_acq_cancel_reason($reason_id);
748 my ($cancel_count, $fatal) =
749 $class->cancel_lids($e, $reason, $remaining_lids, $lid_count, \@lids);
752 $lids_cancelled += $cancel_count;
754 # All LIDs cancelled with same reason, apply
755 # the same cancel reason to the lineitem
756 if ($remaining_lids == $order_qty) {
757 $li->cancel_reason($reason->id);
758 $li->state("cancelled");
761 $li->edit_time('now');
762 unless ($e->update_acq_lineitem($li)) {
763 $logger->error("EDI: update_acq_lineitem failed " . $e->die_event);
768 $logger->warn("EDI: vendor says we ordered $order_qty and cancelled ".
769 "$lids_cancelled, but only shipped $dispatch_qty");
774 # LI and LIDs updated, let's wrap this one up.
775 # this is a no-op if the xact has already been rolled back
778 $logger->info("EDI: LI $li_id -- $order_qty LIDs ordered; ".
779 "$lids_cancelled LIDs cancelled");
784 my ($class, $e, $reason, $count, $lid_count, $lid_ids) = @_;
786 my $cancel_count = 0;
788 foreach (1 .. $count) {
790 my $lid_id = shift @$lid_ids;
793 $logger->warn("EDI: Used up all $lid_count LIDs. ".
794 "Ignoring extra status '" . $reason->label . "'");
798 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
799 $lid->cancel_reason($reason->id);
801 # item is cancelled. Remove the fund debit.
802 unless ($U->is_true($reason->keep_debits)) {
804 if (my $debit_id = $lid->fund_debit) {
806 $lid->clear_fund_debit;
807 my $debit = $e->retrieve_acq_fund_debit($debit_id);
809 if ($U->is_true($debit->encumbrance)) {
810 $logger->info("EDI: deleting debit $debit_id for cancelled LID $lid_id");
812 unless ($e->delete_acq_fund_debit($debit)) {
813 $logger->error("EDI: unable to update fund_debit " . $e->die_event);
817 # do not delete a paid-for debit
818 $logger->warn("EDI: cannot delete invoiced debit $debit_id");
823 $e->update_acq_lineitem_detail($lid);
827 return ($cancel_count);
830 sub edi_date_to_iso {
831 my ($class, $date) = @_;
832 return undef unless $date and $date =~ /\d+/;
833 my ($iso, $m, $d) = $date =~ /^(\d{4})(\d{2})(\d{2})/g;
840 # Return hash with a key for every kludge that should apply for this
841 # msg_type (INVOIC,ORDRSP) and this vendor SAN.
843 my ($class, $msg_type, $vendor_san) = @_;
846 while (my ($kludge, $vendors) = each %{$VENDOR_KLUDGE_MAP->{$msg_type}}) {
847 push @kludges, $kludge if grep { $_ eq $vendor_san } @$vendors;
850 return map { $_ => 1 } @kludges;
853 # create_acq_invoice_from_edi() does what it sounds like it does for INVOIC
854 # messages. For similar operation on ORDRSP messages, see the guts of
856 # Return boolean success indicator.
857 sub create_acq_invoice_from_edi {
858 my ($class, $msg_data, $provider, $message) = @_;
859 # $msg_data is O::U::EDIReader hash
860 # $provider is only a pkey
861 # $message is Fieldmapper::acq::edi_message
863 my $e = new_editor();
865 my $log_prefix = "create_acq_invoice_from_edi(..., <acq.edi_message #" .
866 $message->id . ">): ";
869 if ($msg_data->{vendor_san}) {
870 %msg_kludges = $class->get_kludges('INVOIC', $msg_data->{vendor_san});
872 $logger->warn($log_prefix . "no vendor_san field!");
875 my $eg_inv = Fieldmapper::acq::invoice->new;
878 # Some troubleshooting aids. Yeah we should have made appropriate links
879 # for this in the schema, but this is better than nothing. Probably
880 # *don't* try to i18n this.
881 $eg_inv->note("Generated from acq.edi_message #" . $message->id . ".");
885 " Vendor kludges: " . join(", ", keys(%msg_kludges)) . "."
889 $eg_inv->provider($provider);
890 $eg_inv->shipper($provider); # XXX Do we really have a meaningful way to
891 # distinguish provider and shipper?
892 $eg_inv->recv_method("EDI");
895 $class->edi_date_to_iso($msg_data->{invoice_date}));
898 $class->process_message_buyer($e, $msg_data, $message, $log_prefix, $eg_inv);
900 if (!$eg_inv->receiver) {
902 sprintf("unable to determine buyer (org unit) in invoice; ".
903 "buyer_san=%s; buyer_acct=%s",
904 ($msg_data->{buyer_san} || ''),
905 ($msg_data->{buyer_acct} || '')
910 $eg_inv->inv_ident($msg_data->{invoice_ident});
912 if (!$eg_inv->inv_ident) {
913 die($log_prefix . "no invoice ID # in INVOIC message; " . shift);
918 $message->purchase_order($msg_data->{purchase_order});
920 for my $lineitem (@{$msg_data->{lineitems}}) {
921 my $li_id = $lineitem->{id};
924 $logger->warn($log_prefix . "no lineitem ID");
928 my $li = $e->retrieve_acq_lineitem($li_id);
931 die($log_prefix . "no LI found with ID: $li_id : " . $e->event);
934 my ($quant) = grep {$_->{code} eq '47'} @{$lineitem->{quantities}};
935 my $quantity = ($quant) ? $quant->{quantity} : 0;
938 $logger->warn($log_prefix .
939 "no invoice quantity specified for LI $li_id");
943 # NOTE: if needed, we also have $lineitem->{net_unit_price}
944 # and $lineitem->{gross_unit_price}
945 my $lineitem_price = $lineitem->{amount_billed};
947 # XXX Should we set acqie.billed_per_item=t in this case instead? Not
948 # sure whether that actually works everywhere it needs to. LFW
949 $lineitem_price *= $quantity if $msg_kludges{amount_billed_is_per_unit};
951 # if the top-level PO value is unset, get it from the first LI
952 $message->purchase_order($li->purchase_order)
953 unless $message->purchase_order;
955 my $eg_inv_entry = Fieldmapper::acq::invoice_entry->new;
956 $eg_inv_entry->isnew(1);
957 $eg_inv_entry->inv_item_count($quantity);
959 # amount staff agree to pay for
960 $eg_inv_entry->phys_item_count($quantity);
962 # XXX Validate by making sure the LI is on-order and belongs to
963 # the right provider and ordering agency and all that.
964 $eg_inv_entry->lineitem($li_id);
966 # XXX Do we actually need to link to PO directly here?
967 $eg_inv_entry->purchase_order($li->purchase_order);
969 # This is the total price for all units billed, not per-unit.
970 $eg_inv_entry->cost_billed($lineitem_price);
972 # amount staff agree to pay
973 $eg_inv_entry->amount_paid($lineitem_price);
975 push @eg_inv_entries, $eg_inv_entry;
977 # The EDIReader class does detect certain per-lineitem taxes, but
978 # we'll ignore them for now, as the only sample invoices I've yet seen
979 # containing them also had a final cumulative tax at the end.
984 my %charge_type_map = (
985 'TX' => ['TAX', 'Tax from electronic invoice'],
986 'CA' => ['PRO', 'Cataloging services'],
987 'DL' => ['SHP', 'Delivery'],
988 'GST' => ['TAX', 'Goods and services tax']
989 ); # XXX i18n, somehow
991 for my $charge (@{$msg_data->{misc_charges}}, @{$msg_data->{taxes}}) {
992 my $eg_inv_item = Fieldmapper::acq::invoice_item->new;
993 $eg_inv_item->isnew(1);
995 my $amount = $charge->{amount};
998 $logger->warn($log_prefix . "charge with no amount");
1002 my $map = $charge_type_map{$charge->{type}};
1005 $map = ['PRO', 'Misc / unspecified'];
1006 $eg_inv_item->note($charge->{type});
1009 $eg_inv_item->inv_item_type($$map[0]);
1010 $eg_inv_item->title($$map[1]); # title is user-visible; note isn't.
1011 $eg_inv_item->cost_billed($amount);
1012 $eg_inv_item->amount_paid($amount);
1014 push @eg_inv_items, $eg_inv_item;
1017 $logger->info($log_prefix .
1018 sprintf("creating invoice with %d entries and %d items.",
1019 scalar(@eg_inv_entries), scalar(@eg_inv_items)));
1023 # save changes to acq.edi_message row
1024 if (not $e->update_acq_edi_message($message)) {
1025 die($log_prefix . "couldn't update edi_message " . $message->id);
1028 my $result = OpenILS::Application::Acq::Invoice::build_invoice_impl(
1029 $e, $eg_inv, \@eg_inv_entries, \@eg_inv_items, 0 # don't commit yet
1032 if ($U->event_code($result)) {
1033 die($log_prefix. "build_invoice_impl() failed: " . $result->{textcode});