6 use File::Temp 'tempdir';
8 use FS::UID qw(adminsuidsetup datasrc dbh);
11 use FS::Record qw(qsearch qsearchs);
12 use Date::Format 'time2str';
13 use Date::Parse 'str2time';
20 use vars qw( $opt_d $opt_v $opt_c $opt_s $opt_e $opt_a );
23 my ($user, $login, $password) = @ARGV;
24 ($user and $login and $password) or die &usage;
26 my $dbh = adminsuidsetup $user;
27 $FS::UID::AutoCommit = 0;
29 # index already-downloaded batches
30 my @previous = qsearch({
31 'table' => 'cdr_batch',
32 'hashref' => { 'cdrbatch' => {op=>'like', value=>'thinktel%'} },
33 'order_by' => 'ORDER BY cdrbatch DESC',
35 my %exists = map {$_->cdrbatch => 1} @previous;
37 my $tempdir = tempdir( CLEANUP => !$opt_v );
39 my $format = 'thinktel';
40 my $hostname = 'ucontrol.thinktel.ca';
42 my $ftp = Net::FTP->new($hostname, Debug => $opt_d)
43 or die "Can't connect to $hostname: $@\n";
45 $ftp->login($login, $password)
46 or die "Login failed: ".$ftp->message."\n";
52 warn "Retrieving directory listing\n" if $opt_v;
55 my @files = grep { $_ =~ /MetaSwitch/ } $ftp->ls();
57 warn scalar(@files)." CDR files found.\n" if $opt_v;
60 my $most_recent = $previous[0];
62 if ($most_recent->cdrbatch =~ /^thinktel-(\d+)/) {
64 warn "limiting to dates > $date (from most recent batch)\n" if $opt_v;
65 @files = grep { /^(\d+)_/ && $1 > $date } @files;
67 } # else download them all
71 # normalize date format
72 $opt_s = time2str('%Y%m%d', str2time($opt_s)) if $opt_s =~ /\D/;
73 warn "limiting to dates > $opt_s\n" if $opt_v;
74 @files= grep { /^(\d+)_/ && $1 >= $opt_s } @files;
78 $opt_e = time2str('%Y%m%d', str2time($opt_e)) if $opt_e =~ /\D/;
79 warn "limiting to dates < $opt_e\n" if $opt_v;
80 @files= grep { /^(\d+)_/ && $1 < $opt_e } @files;
82 warn scalar(@files) ." files to be downloaded to '$tempdir'\n" if $opt_v;
83 foreach my $file (@files) {
85 warn "downloading $file\n" if $opt_v;
86 $ftp->get($file, "$tempdir/$file");
87 warn "processing $file\n" if $opt_v;
89 my $batchname = "$format-$file";
90 if ($exists{$batchname}) {
91 warn "already imported $file\n";
94 my $import_options = {
95 'file' => "$tempdir/$file",
97 'batch_namevalue' => $batchname,
100 $import_options->{'cdrtypenum'} = $opt_c if $opt_c;
102 my $error = FS::cdr::batch_import($import_options);
105 die "error processing $file: $error\n";
108 warn "finished\n" if $opt_v;
116 "Usage: \n cdr-thinktel.import [ options ] user login password
119 -d: enable FTP debugging (very noisy)
120 -c num: apply a cdrtypenum to the imported CDRs
123 -a: automatically choose start date from most recently downloaded batch