]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/support-scripts/edi_pusher.pl
LP2042879 Shelving Location Groups Admin accessibility
[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     'test'  => 0,   # TODO
36     'max-batch-size=i' => -1,
37
38     # if true, print final EDI to STDOUT, send nothign to the vendor, write nothing to the DB
39     'debug-only' => 0
40 );
41
42 my $cs = OpenILS::Utils::Cronscript->new(\%defaults);
43
44 my $opts = $cs->MyGetOptions();
45 my $e    = $cs->editor() or die "Failed to get new CStoreEditor";
46 my $hook = 'acqpo.activated';
47 my $defs = $e->search_action_trigger_event_definition({
48     hook    => $hook,
49     reactor => 'GeneratePurchaseOrderJEDI',
50     active  => 't'
51 });
52
53 $opts->{verbose} = 0 if $opts->{quiet};
54
55 print "FTP_PASSIVE is ", ($ENV{FTP_PASSIVE} ? "ON" : "OFF"),  "\n";
56
57 print "\nHook '$hook' is used in ", scalar(@$defs), " event definition(s):\n";
58
59 $Data::Dumper::Indent = 1;
60 my $remaining = $opts->{'max-batch-size'};
61
62 # FIXME: this is the disclusion subquery.  It discludes any PO that has
63 # a non-retry edi_message linked to it.  But that means that if there are
64 # mutliple EDI messages (say, some failed translation) and one marked retry,
65 # the PO is still discluded!  Perhaps there should never be multiple messages,
66 # but that makes testing much trickier (and is not DB-enforced).
67 #
68 # One approach might be to supplementally query for any "retry" messages that 
69 # are on active providers (and deduplicate).  
70
71 my $subq = {
72     select => { acqedim => ['purchase_order'] },
73     from   => 'acqedim',
74     where  => {
75         message_type   => 'ORDERS',
76         status         => {'!=' => 'retry' },
77         purchase_order => {'!=' => undef   }
78     }
79 };
80
81 foreach my $def (@$defs) {
82     last if $remaining == 0;
83     printf "%3s - '%s'\n", $def->id, $def->name;
84
85     # give me all completed JEDI events that link to purchase_orders 
86     # that have no delivery attempts or are in the retry state
87
88     my $query = {
89         select => {atev => ['id']},
90         from   => 'atev',
91         where  => {
92             event_def => $def->id,
93             state  => 'complete',
94             target => {
95                 'not in' => $subq
96             }
97         },
98         order_by => {atev => ['add_time']}
99     };
100
101     $query->{limit} = $remaining if $remaining > 0;
102
103     if ($opts->{verbose}) {
104         # $subq->{'select'}->{'acqedim'} = ['id', 'purchase_order', 'message_type', 'status'];
105         my $excluded = $e->json_query($subq);
106         print "Excluded: ", scalar(@$excluded), " purchase order(s):\n";
107         my $z = 0;
108         print map {sprintf "%7d%s", $_, (++$z % 5) ? '' : "\n"} sort {$a <=> $b} map {$_->{purchase_order}} @$excluded;
109         print "\n";
110     }
111
112     my $events = $e->json_query($query);
113
114     if(!$events) {
115         print STDERR   "error querying JEDI events for event definition ", $def->id, "\n";
116         $logger->error("error querying JEDI events for event definition ". $def->id);
117         next;
118     }
119
120     $remaining -= scalar(@$events);
121
122     print "Event definition ", $def->id, " has ", scalar(@$events), " (completed) event(s)\n";
123     foreach (@$events) {
124
125         my $event = $e->retrieve_action_trigger_event([
126             $_->{id}, 
127             {flesh => 1, flesh_fields => {atev => ['template_output']}}
128         ]);
129
130
131         my $target = $e->retrieve_acq_purchase_order([              # instead we retrieve it separately
132             $event->target, {
133                 flesh => 2,
134                 flesh_fields => {
135                     acqpo  => ['provider'],
136                     acqpro => ['edi_default'],
137                 },
138             }
139         ]);
140
141         # this may be a retry attempt.  if so, reuse the original edi_message
142         my $message = $e->search_acq_edi_message({
143             purchase_order => $target->id,
144             message_type => 'ORDERS', 
145             status => 'retry'
146         })->[0];
147
148         if(!$message) {
149             $message = Fieldmapper::acq::edi_message->new;
150             $message->create_time('NOW');   # will need this later when we try to update from the object
151             $message->purchase_order($target->id);
152             $message->message_type('ORDERS');
153             $message->isnew(1);
154         }
155
156         my $logstr = sprintf "provider %s (%s)", $target->provider->id, $target->provider->name;
157         unless ($target->provider->edi_default and $message->account($target->provider->edi_default->id)) {
158             printf STDERR "ERROR: No edi_default account found for $logstr.  File will not be sent!\n";
159         }
160
161         $message->jedi($event->template_output()->data);
162
163         print "\ntarget->provider->edi_default->id: ", $target->provider->edi_default->id, "\n";
164         my $logstr2 = sprintf "event %s, PO %s, template_output %s", $_->{id}, $message->purchase_order, $event->template_output->id;
165         if ($opts->{test}) {
166             print "Test mode, skipping translation/send\n";
167             next;
168         }
169
170         printf "\nNow calling attempt_translation for $logstr2\n\n";
171
172         unless (OpenILS::Application::Acq::EDI->attempt_translation($message, 1)) {
173             print STDERR "ERROR: attempt_translation failed for $logstr2\n";
174             next;
175             # The premise here is that if the translator failed, it is better to try again later from a "fresh" fetched file
176             # than to add a cascade of failing inscrutable copies of the same message(s) to our DB.  
177         }
178
179         if ($opts->{'debug-only'}) {
180             print OpenILS::Application::Acq::EDI->attempt_translation($message, 1)->edi . "\n";
181             print "\ndebug-only => skipping FTP\n";
182             next;
183         }
184
185         print "Writing new message + translation to DB for $logstr2\n";
186
187         $e->xact_begin;
188         if($message->isnew) {
189             unless($e->create_acq_edi_message($message)) {
190                 $logger->error("Error creating acq.edi_message for $logstr2: ".$e->die_event);
191                 next;
192             }
193         } else {
194             unless($e->update_acq_edi_message($message)) {
195                 $logger->error("Error updating acq.edi_message for $logstr2: ".$e->die_event);
196                 next;
197             }
198         }
199         $e->xact_commit;
200
201         print "Calling send_core(...) for message (", $message->id, ")\n";
202         my $res = OpenILS::Application::Acq::EDI->send_core($target->provider->edi_default, [$message->id]);
203         if (@$res) {
204             my $message_out = shift @$res;
205             print "\tmessage ", $message->id, " status: ", $message_out->status, "\n";
206         } else {
207             print STDERR "ERROR: send_core failed for message ", $message->id, "\n";
208         }
209     }
210 }
211
212 print "\ndone\n";
213
214 __END__
215
216 =head1 NAME
217
218 edi_pusher.pl - A script for generating and sending EDI files to remote accounts.
219
220 =head1 DESCRIPTION
221
222 This script is expected to be run via crontab, for the purpose of retrieving vendor EDI files.
223
224 =head1 OPTIONS
225
226   --max-batch-size=i  Limit the processing to a set number of events.
227
228 =head1 TODO
229
230 More docs here.
231
232 =head1 USAGE
233
234 B<FTP_PASSIVE=1> is recommended.  Depending on your vendors' and your own network environments, you may want to set/export
235 the environmental variable FTP_PASSIVE like:
236
237     export FTP_PASSIVE=1
238     # or
239     FTP_PASSIVE=1 Open-ILS/src/support-scripts/edi_pusher.pl
240
241 =head1 SEE ALSO
242
243     OpenILS::Utils::Cronscript
244     edi_fetcher.pl
245
246 =head1 AUTHOR
247
248 Joe Atzberger <jatzberger@esilibrary.com>
249
250 =cut