invoice_sections_with_taxes per-agent, RT#79636
[freeside.git] / FS / bin / freeside-cdr-telapi-import
1 #!/usr/bin/perl
2
3 use strict;
4
5 use Date::Format 'time2str';
6 use Date::Parse 'str2time';
7 use Getopt::Long;
8 use Cpanel::JSON::XS;
9 use Net::HTTPS::Any qw(https_post https_get);
10 use Time::Local;
11
12 use FS::Record qw(qsearchs dbh);
13 use FS::UID qw(adminsuidsetup);
14 use FS::cdr;
15 use FS::cdr_batch;
16
17 my $host = "cdr.teleapi.net";
18
19 my @now = localtime();
20 my $now = timelocal($now[0],$now[1],$now[2],$now[3],$now[4],$now[5]); #most recent midnight
21
22 sub usage {
23   "Usage:
24 freeside-cdr-telapi-import -t type -p token -s startdate [-e enddate] freesideuser
25
26 Downloads any existing CDR voip files or CDR SMS files (type) from the start date untill the enddate and 
27 imports those records.";
28 }
29
30 my ($type,$token,$startdate,$enddate);
31 GetOptions(
32   "type=s"      => \$type,
33   "token=s"     => \$token,
34   "startdate=s" => \$startdate,
35   "enddate=s"   => \$enddate,
36 );
37
38 my $fsuser = $ARGV[-1];
39
40 die usage() unless $fsuser;
41
42 adminsuidsetup($fsuser);
43
44 my ( $page, $response, %reply_headers )= https_get(
45       'host' => $host,
46       'port' => '443',
47       'path' => '/'.$type.'/'.$startdate.'/'.$enddate.'?token='.$token,
48     );
49
50 die "Bad response from telapi server: $response"
51   unless $response =~ /^200/;
52
53 my $cdrbatch = "Telapi-import-" . $type . "-" . time2str('%Y/%m/%d-%T',$now);  
54
55 my $dir = $FS::UID::cache_dir. "/cache.". $FS::UID::datasrc; 
56
57 my $cfh = new File::Temp( TEMPLATE => 'telapi.XXXXXXXX',
58                           SUFFIX   => '.csv',
59                           DIR      => $dir,
60                          )
61     or die "can't open temporary file to save data: $!\n";
62
63 #print returned data to file handle for temp file.
64 print $cfh $page;
65
66 seek($cfh,0,0);
67
68   print "Importing batch $cdrbatch\n";
69   my $error = FS::cdr::batch_import({
70     'batch_namevalue' => $cdrbatch,
71     'file'            => $cfh->filename,
72     'format'          => 'telapi_'.$type
73   });
74
75 exit;