summaryrefslogtreecommitdiff
path: root/FS/bin/freeside-eftca-download
blob: 1b7653cb39a6e633dcfe7a2ebcc3b86f5c8c01f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/perl

use strict;
use Getopt::Std;
use Date::Format qw(time2str);
use File::Temp qw(tempdir);
use Net::SFTP::Foreign;
use Expect;
use FS::UID qw(adminsuidsetup datasrc);
use FS::Record qw(qsearch qsearchs);
use FS::pay_batch;
use FS::cust_pay_batch;
use FS::Conf;

use vars qw( $opt_v $opt_a );
getopts('va:');

#$Net::SFTP::Foreign::debug = -1;
sub HELP_MESSAGE { "
  Usage:
      freeside-eftca-download [ -v ] [ -a archivedir ] user\n
" }

my @fields = (
  'tid',          # transaction ID
  'paybatchnum',  # reference field
  'returncode',   # status code
  'returndate',
  'paid',         # dollars and cents, with decimal
  'type',
  'first',
  'last',
  'account',
  'bank',
  'transit',
);

my $user = shift or die &HELP_MESSAGE;
adminsuidsetup $user;

if ( $opt_a ) {
  die "no such directory: $opt_a\n"
    unless -d $opt_a;
  die "archive directory $opt_a is not writable by the freeside user\n"
    unless -w $opt_a;
}

#my $tmpdir = File::Temp->newdir();
my $tmpdir = tempdir( CLEANUP => 1 ); #DIR=>somewhere?

my $conf = new FS::Conf;

my @agents;
if ( $conf->exists('batch-spoolagent') ) {
  @agents = qsearch('agent', { 'disabled' => '' });
} else {
  @agents = (1);
}

foreach my $agent (@agents) {

  my @batchconf;
  if ( $conf->exists('batch-spoolagent') ) {
    @batchconf = $conf->config('batchconfig-eft_canada', $agent->agentnum, 1);
    if ( !length($batchconf[0]) ) {
      warn "agent '".$agent->agent."' has no batchconfig-eft_canada setting; skipped.\n";
      next;
    }
  } else {
    @batchconf = $conf->config('batchconfig-eft_canada');
  }
  # user, password, transaction code, delay days
  my $user = $batchconf[0] or die "no EFT Canada batch username configured\n";
  my $pass = $batchconf[1] or die "no EFT Canada batch password configured\n";

  my $host = 'ftp.eftcanada.com';
  print STDERR "Connecting to $user\@$host...\n" if $opt_v;

  my $sftp = Net::SFTP::Foreign->new( host     => $host,
                                      user     => $user,
                                      password => $pass,
                                      timeout  => 30,
                                    );
  die "failed to connect to '$user\@$host'\n(".$sftp->error.")\n" if $sftp->error;

  $sftp->setcwd('/Returns');

  my $files = $sftp->ls('.', wanted => qr/\.txt$/, names_only => 1);
  die "no response files found\n" if !@$files;

  FILE: foreach my $filename (@$files) {
    print STDERR "Retrieving $filename\n" if $opt_v;
    $sftp->get("$filename", "$tmpdir/$filename");
    if($sftp->error) {
      warn "failed to download $filename\n";
      next FILE;
    }

    #move to server archive dir
    $sftp->rename("$filename", "Archive/$filename");
    if($sftp->error) {
      warn "failed to archive $filename on server\n";
    } # process it anyway though

    #copy to local archive dir
    if ( $opt_a ) {
      print STDERR "Copying $tmpdir/$filename to archive dir $opt_a\n"
        if $opt_v;
      system 'cp', "$tmpdir/$filename", $opt_a;
      warn "failed to copy $tmpdir/$filename to $opt_a: $@" if $@;
    }

    open my $fh, "<$tmpdir/$filename";
    # Some duplication with FS::pay_batch::import_results, but we're really 
    # doing something different here.
    my $csv = new Text::CSV_XS ( { quote_char => undef, sep_char => '|' } );
    my %hash;
    while (my $line = <$fh>) {
      next if $line =~ /^\s*$/;
      $csv->parse($line) or do {
        warn "can't parse $filename: ".$csv->error_input."\n";
        next FILE; #parsing errors = reading the wrong kind of file
      };
      @hash{@fields} = $csv->fields();
      print STDERR "voiding paybatchnum#$hash{paybatchnum}\n" if $opt_v;
      my $cpb = qsearchs('cust_pay_batch', 
                          { paybatchnum => $hash{'paybatchnum'} });
      if ( !$cpb ) {
        warn "can't find paybatchnum #$hash{paybatchnum} ($hash{first} $hash{last}, $hash{paid})\n";
        next;
      }
      my $error = $cpb->decline("Returned payment ($hash{returncode})");
      if ( $error ) {
        warn "can't void paybatchnum #$hash{paybatchnum}: $error\n";
      }
    }
    close $fh;
  }

}

print STDERR "Finished!\n" if $opt_v;

=head1 NAME

freeside-eftca-download - Retrieve payment batch responses from EFT Canada.

=head1 SYNOPSIS

  freeside-eftca-download [ -v ] [ -a archivedir ] user

=head1 DESCRIPTION

Command line tool to download returned payment reports from the EFT Canada 
gateway and void the returned payments.  Uses the login and password from 
'batchconfig-eft_canada'.

-v: Be verbose.

-a directory: Archive response files in the provided directory.

user: freeside username

=head1 BUGS

You need to manually SFTP to ftp.eftcanada.com from the freeside account 
and accept their key before running this script.

=head1 SEE ALSO

L<FS::pay_batch>

=cut

1;