Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / bin / cdr-voip_ms.import
1 #!/usr/bin/perl
2
3 use strict;
4 use FS::Misc::Getopt;
5 use FS::cdr_batch;
6 use FS::part_export;
7 use FS::Record qw(qsearch qsearchs dbh);
8 use Date::Format 'time2str';
9
10 ###
11 # parse command line
12 ###
13
14 our %opt;
15 getopts('');
16
17 $FS::UID::AutoCommit = 0;
18
19 my @exports = qsearch('part_export', { exporttype => 'voip_ms' });
20 if (!@exports) {
21   die "There are no voip.ms exports configured.\n";
22 }
23
24 foreach my $part_export (@exports) {
25   debug "Account #".$part_export->option('account');
26
27   if (!$opt{start}) {
28     # find the most recently downloaded batch
29     my $exportnum = $part_export->exportnum;
30     my $most_recent = qsearchs({
31         'table'     => 'cdr_batch',
32         'hashref'   => { 'cdrbatch' => {op=>'like',
33                                         value=>'voip_ms-' . $exportnum . '-%'}
34                        },
35         'order_by'  => 'ORDER BY _date DESC LIMIT 1',
36     });
37     if ( $most_recent ) {
38       $most_recent->cdrbatch =~ /-(\d+)$/; # extract the end timestamp
39       $opt{start} = $1;
40       debug "Downloading records since most recent batch: ".
41             time2str('%Y-%m-%d', $opt{start});
42     } else {
43       $opt{start} = 1262332800;
44       debug "Downloading records since January 2010.";
45     }
46   }
47
48   $opt{end} ||= time;
49
50   my $error_or_batch = $part_export->import_cdrs( $opt{start}, $opt{end} );
51   if ( ref $error_or_batch ) {
52     debug "Created batch #".$error_or_batch->cdrbatchnum;
53     dbh->commit;
54   } elsif ( $error_or_batch ) {
55     warn $error_or_batch;
56     dbh->rollback;
57   } else {
58     debug "No CDRs found."
59   }
60 }
61
62 sub usage {
63   "Usage: \n  cdr-voip_ms.import [ options ] user
64   Options:
65     -v: be verbose
66     -s date: start date (defaults to the most recent batch date)
67     -e date: end date
68 ";
69 }
70