]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/support-scripts/edi_pusher.pl
bb214da52be812bb375154109b248910ea1c0044
[working/Evergreen.git] / Open-ILS / src / support-scripts / edi_pusher.pl
1 #!/usr/bin/perl
2 # ---------------------------------------------------------------
3 # Copyright (C) 2010 Equinox Software, Inc
4 # Author: Joe Atzberger <jatzberger@esilibrary.com>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 # ---------------------------------------------------------------
16
17 use strict;
18 use warnings;
19
20 use Data::Dumper;
21 use vars qw/$debug/;
22
23 use OpenILS::Utils::Cronscript;
24 use OpenILS::Utils::Fieldmapper;
25 use OpenILS::Application::AppUtils;
26 use OpenILS::Application::Acq::EDI;
27 use OpenSRF::Utils::Logger q/$logger/;
28
29 INIT {
30     $debug = 1;
31 }
32
33 my %defaults = (
34     'quiet' => 0,
35     'max-batch-size=i' => -1
36 );
37
38 my $cs = OpenILS::Utils::Cronscript->new(\%defaults);
39
40 my $opts = $cs->MyGetOptions();
41 my $e    = $cs->editor() or die "Failed to get new CStoreEditor";
42 my $hook = 'acqpo.activated';
43 my $defs = $e->search_action_trigger_event_definition({
44     hook    => $hook,
45     reactor => 'GeneratePurchaseOrderJEDI',
46     active  => 't'
47 });
48
49 $opts->{verbose} = 0 if $opts->{quiet};
50
51 print "\nHook '$hook' is used in ", scalar(@$defs), " event definition(s):\n";
52
53 $Data::Dumper::Indent = 1;
54 my $remaining = $opts->{'max-batch-size'};
55
56 # FIXME: this is the disclusion subquery.  It discludes any PO that has
57 # a non-retry edi_message linked to it.  But that means that if there are
58 # mutliple EDI messages (say, some failed translation) and one marked retry,
59 # the PO is still discluded!  Perhaps there should never be multiple messages,
60 # but that makes testing much trickier (and is not DB-enforced).
61 #
62 # One approach might be to supplementally query for any "retry" messages that 
63 # are on active providers (and deduplicate).  
64
65 my $subq = {
66     select => { acqedim => ['purchase_order'] },
67     from   => 'acqedim',
68     where  => {
69         message_type   => 'ORDERS',
70         status         => {'!=' => 'retry' },
71         purchase_order => {'!=' => undef   }
72     }
73 };
74
75 foreach my $def (@$defs) {
76     last if $remaining == 0;
77     printf "%3s - '%s'\n", $def->id, $def->name;
78
79     # give me all completed JEDI events that link to purchase_orders 
80     # that have no delivery attempts or are in the retry state
81
82     my $query = {
83         select => {atev => ['id']},
84         from   => 'atev',
85         where  => {
86             event_def => $def->id,
87             state  => 'complete',
88             target => {
89                 'not in' => $subq
90             }
91         },
92         order_by => {atev => ['add_time']}
93     };
94
95     $query->{limit} = $remaining if $remaining > 0;
96
97     if ($opts->{verbose}) {
98         # $subq->{'select'}->{'acqedim'} = ['id', 'purchase_order', 'message_type', 'status'];
99         my $excluded = $e->json_query($subq);
100         print "Excluded: ", scalar(@$excluded), " purchase order(s):\n";
101         print join("\n", sort map {sprintf "%7d", $_->{purchase_order}} @$excluded), "\n";
102     }
103
104     my $events = $e->json_query($query);
105
106     if(!$events) {
107         print STDERR   "error querying JEDI events for event definition ", $def->id, "\n";
108         $logger->error("error querying JEDI events for event definition ". $def->id);
109         next;
110     }
111
112     $remaining -= scalar(@$events);
113
114     print "Event definition ", $def->id, " has ", scalar(@$events), " (completed) event(s)\n";
115     foreach (@$events) {
116
117         my $event = $e->retrieve_action_trigger_event([
118             $_->{id}, 
119             {flesh => 1, flesh_fields => {atev => ['template_output']}}
120         ]);
121
122
123         my $target = $e->retrieve_acq_purchase_order([              # instead we retrieve it separately
124             $event->target, {
125                 flesh => 2,
126                 flesh_fields => {
127                     acqpo  => ['provider'],
128                     acqpro => ['edi_default'],
129                 },
130             }
131         ]);
132
133         # this may be a retry attempt.  if so, reuse the original edi_message
134         my $message = $e->search_acq_edi_message({
135             purchase_order => $target->id,
136             message_type => 'ORDERS', 
137             status => 'retry'
138         })->[0];
139
140         if(!$message) {
141             $message = Fieldmapper::acq::edi_message->new;
142             $message->create_time('NOW');   # will need this later when we try to update from the object
143             $message->purchase_order($target->id);
144             $message->message_type('ORDERS');
145             $message->isnew(1);
146         }
147
148         my $logstr = sprintf "provider %s (%s)", $target->provider->id, $target->provider->name;
149         unless ($target->provider->edi_default and $message->account($target->provider->edi_default->id)) {
150             printf STDERR "ERROR: No edi_default account found for $logstr.  File will not be sent!\n";
151         }
152
153         $message->jedi($event->template_output()->data);
154
155         print "\ntarget->provider->edi_default->id: ", $target->provider->edi_default->id, "\n";
156         my $logstr2 = sprintf "event %s, PO %s, template_output %s", $_->{id}, $message->purchase_order, $event->template_output->id;
157         printf "\nNow calling attempt_translation for $logstr2\n\n";
158
159         unless (OpenILS::Application::Acq::EDI->attempt_translation($message, 1)) {
160             print STDERR "ERROR: attempt_translation failed for $logstr2\n";
161             next;
162             # The premise here is that if the translator failed, it is better to try again later from a "fresh" fetched file
163             # than to add a cascade of failing inscrutable copies of the same message(s) to our DB.  
164         }
165
166         print "Writing new message + translation to DB for $logstr2\n";
167
168         $e->xact_begin;
169         if($message->isnew) {
170             unless($e->create_acq_edi_message($message)) {
171                 $logger->error("Error creating acq.edi_message for $logstr2: ".$e->die_event);
172                 next;
173             }
174         } else {
175             unless($e->update_acq_edi_message($message)) {
176                 $logger->error("Error updating acq.edi_message for $logstr2: ".$e->die_event);
177                 next;
178             }
179         }
180         $e->xact_commit;
181
182         print "Calling send_core(...) for message (", $message->id, ")\n";
183         my $res = OpenILS::Application::Acq::EDI->send_core($target->provider->edi_default, [$message->id]);
184         if (@$res) {
185             my $message_out = shift @$res;
186             print "\tmessage ", $message->id, " status: ", $message_out->status, "\n";
187         } else {
188             print STDERR "ERROR: send_core failed for message ", $message->id, "\n";
189         }
190     }
191 }
192
193 print "\ndone\n";