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 = $ftp->ls();
56 warn scalar(@files)." CDR files found.\n" if $opt_v;
59 my $most_recent = $previous[0];
61 if ($most_recent->cdrbatch =~ /^thinktel-(\d+)/) {
63 warn "limiting to dates > $date (from most recent batch)\n" if $opt_v;
64 @files = grep { /^(\d+)_/ && $1 > $date } @files;
66 } # else download them all
70 # normalize date format
71 $opt_s = time2str('%Y%m%d', str2time($opt_s)) if $opt_s =~ /\D/;
72 warn "limiting to dates > $opt_s\n" if $opt_v;
73 @files= grep { /^(\d+)_/ && $1 >= $opt_s } @files;
77 $opt_e = time2str('%Y%m%d', str2time($opt_e)) if $opt_e =~ /\D/;
78 warn "limiting to dates < $opt_e\n" if $opt_v;
79 @files= grep { /^(\d+)_/ && $1 < $opt_e } @files;
81 warn scalar(@files) ." files to be downloaded to '$tempdir'\n" if $opt_v;
82 foreach my $file (@files) {
84 warn "downloading $file\n" if $opt_v;
85 $ftp->get($file, "$tempdir/$file");
86 warn "processing $file\n" if $opt_v;
88 my $batchname = "$format-$file";
89 if ($exists{$batchname}) {
90 warn "already imported $file\n";
93 my $import_options = {
94 'file' => "$tempdir/$file",
96 'batch_namevalue' => $batchname,
99 $import_options->{'cdrtypenum'} = $opt_c if $opt_c;
101 my $error = FS::cdr::batch_import($import_options);
104 die "error processing $file: $error\n";
107 warn "finished\n" if $opt_v;
115 "Usage: \n cdr-thinktel.import [ options ] user login password
118 -d: enable FTP debugging (very noisy)
119 -c num: apply a cdrtypenum to the imported CDRs
122 -a: automatically choose start date from most recently downloaded batch