]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/support-scripts/edi_pusher.pl
Allow * in file portion of pathname
[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
52 # print Dumper($defs);
53 print "\nHook '$hook' is used in ", scalar(@$defs), " event definition(s):\n";
54
55 $Data::Dumper::Indent = 1;
56 my $remaining = $opts->{'max-batch-size'};
57
58 # FIXME: this is the disclusion subquery.  It discludes any PO that has
59 # a non-retry edi_message linked to it.  But that means that if there are
60 # mutliple EDI messages (say, some failed translation) and one marked retry,
61 # the PO is still discluded!  Perhaps there should never be multiple messages,
62 # but that makes testing much trickier (and is not DB-enforced).
63 #
64 # One approach might be to supplementally query for any "retry" messages that 
65 # are on active providers (and deduplicate).  
66
67 my $subq = {
68     select => { acqedim => ['purchase_order'] },
69     from   => 'acqedim',
70     where  => {
71         message_type   => 'ORDERS',
72         status         => {'!=' => 'retry' },
73         purchase_order => {'!=' => undef   }
74     }
75 };
76
77 foreach my $def (@$defs) {
78     last if $remaining == 0;
79     printf "%3s - '%s'\n", $def->id, $def->name;
80
81     # give me all completed JEDI events that link to purchase_orders 
82     # that have no delivery attempts or are in the retry state
83
84     my $query = {
85         select => {atev => ['id']},
86         from   => 'atev',
87         where  => {
88             event_def => $def->id,
89             state  => 'complete',
90             target => {
91                 'not in' => $subq
92             }
93         },
94         order_by => {atev => ['add_time']}
95     };
96
97     $query->{limit} = $remaining if $remaining > 0;
98
99     if ($opts->{verbose}) {
100         # $subq->{'select'}->{'acqedim'} = ['id', 'purchase_order', 'message_type', 'status'];
101         my $excluded = $e->json_query($subq);
102         print "Excluded: ", scalar(@$excluded), " purchase order(s):\n", Dumper(\@$excluded), "\n";
103     }
104
105     my $events = $e->json_query($query);
106
107     if(!$events) {
108         print STDERR   "error querying JEDI events for event definition ", $def->id, "\n";
109         $logger->error("error querying JEDI events for event definition ". $def->id);
110         next;
111     }
112
113     $remaining -= scalar(@$events);
114
115     print "Event definition ", $def->id, " has ", scalar(@$events), " event(s)\n";
116     foreach (@$events) {
117
118         my $event = $e->retrieve_action_trigger_event([
119             $_->{id}, 
120             {flesh => 1, flesh_fields => {atev => ['template_output']}}
121         ]);
122
123
124         my $target = $e->retrieve_acq_purchase_order([              # instead we retrieve it separately
125             $event->target, {
126                 flesh => 2,
127                 flesh_fields => {
128                     acqpo  => ['provider'],
129                     acqpro => ['edi_default'],
130                 },
131             }
132         ]);
133
134         # this may be a retry attempt.  if so, reuse the original edi_message
135         my $message = $e->search_acq_edi_message({
136             purchase_order => $target->id,
137             message_type => 'ORDERS', 
138             status => 'retry'
139         })->[0];
140
141         if(!$message) {
142             $message = Fieldmapper::acq::edi_message->new;
143             $message->create_time('NOW');   # will need this later when we try to update from the object
144             $message->purchase_order($target->id);
145             $message->message_type('ORDERS');
146             $message->isnew(1);
147         }
148
149         my $logstr = sprintf "provider %s (%s)", $target->provider->id, $target->provider->name;
150         unless ($target->provider->edi_default and $message->account($target->provider->edi_default->id)) {
151             printf STDERR "ERROR: No edi_default account found for $logstr.  File will not be sent!\n";
152         }
153
154         $message->jedi($event->template_output()->data);
155
156         print "\ntarget->provider->edi_default->id: ", $target->provider->edi_default->id, "\n";
157         my $logstr2 = sprintf "event %s, PO %s, template_output %s", $_->{id}, $message->purchase_order, $event->template_output->id;
158         printf "\nNow calling attempt_translation for $logstr2\n\n";
159
160         unless (OpenILS::Application::Acq::EDI->attempt_translation($message, 1)) {
161             print STDERR "ERROR: attempt_translation failed for $logstr2\n";
162             next;
163             # The premise here is that if the translator failed, it is better to try again later from a "fresh" fetched file
164             # than to add a cascade of failing inscrutable copies of the same message(s) to our DB.  
165         }
166
167         print "Writing new message + translation to DB for $logstr2\n";
168
169         $e->xact_begin;
170         if($message->isnew) {
171             unless($e->create_acq_edi_message($message)) {
172                 $logger->error("Error creating acq.edi_message for $logstr2: ".$e->die_event);
173                 next;
174             }
175         } else {
176             unless($e->update_acq_edi_message($message)) {
177                 $logger->error("Error updating acq.edi_message for $logstr2: ".$e->die_event);
178                 next;
179             }
180         }
181         $e->xact_commit;
182
183         print "Calling send_core(...) for message (", $message->id, ")\n";
184         my $res = OpenILS::Application::Acq::EDI->send_core($target->provider->edi_default, [$message->id]);
185         if (@$res) {
186             my $message_out = shift @$res;
187             print "\tmessage ", $message->id, " status: ", $message_out->status, "\n";
188         } else {
189             print STDERR "ERROR: send_core failed for message ", $message->id, "\n";
190         }
191     }
192 }
193
194 print "\ndone\n";