472e2206270aff244bf10d5152b8a1b1c444bde0
[freeside.git] / FS / FS / cdr / Import.pm
1 package FS::cdr::Import;
2
3 use strict;
4 use Date::Format 'time2str';
5 use FS::UID qw(adminsuidsetup dbh);
6 use FS::cdr;
7 use DBI;
8 use Getopt::Std;
9
10 use vars qw( $DEBUG );
11 $DEBUG = 0;
12
13 =head1 NAME
14
15 FS::cdr::Import - CDR importing
16
17 =head1 SYNOPSIS
18
19   use FS::cdr::Import;
20
21   FS::cdr::Import->dbi_import(
22     'dbd'         => 'mysql', #Pg, Sybase, etc.
23     'table'       => 'TABLE_NAME',
24     'primary_key' => 'BILLING_ID',
25     'column_map'  => { #freeside => remote_db
26       'freeside_column' => 'remote_db_column',
27       'freeside_column' => sub { my $row = shift; $row->{remote_db_column}; },
28     },
29   );
30
31 =head1 DESCRIPTION
32
33 CDR importing
34
35 =head1 CLASS METHODS
36
37 =item do_cli_import
38
39 =cut
40
41 sub dbi_import {
42   my $class = shift;
43   my %args = @_; #args are specifed by the script using this sub
44
45   my %opt; #opt is specified for each install / run of the script
46   getopts('H:U:P:D:T:c:L:', \%opt);
47   my $user = shift(@ARGV) or die $class->cli_usage;
48
49   $opt{D} ||= $args{database};
50
51   my $dsn = 'dbi:'. $args{dbd};
52   #$dsn .= ":host=$opt{H}"; #if $opt{H};
53   $dsn .= ":server=$opt{H}"; #if $opt{H};
54   $dsn .= ";database=$opt{D}" if $opt{D};
55
56   my $dbi = DBI->connect($dsn, $opt{U}, $opt{P}) 
57     or die $DBI::errstr;
58
59   adminsuidsetup $user;
60
61   #my $fsdbh = FS::UID::dbh;
62
63   my $table = $opt{T} || $args{table};
64   my $pkey = $args{primary_key};
65
66   #just doing this manually with IVR MSSQL databases for now
67   #  # check for existence of freesidestatus
68   #  my $status = $dbi->selectall_arrayref("SHOW COLUMNS FROM $table WHERE Field = 'freesidestatus'");
69   #  if( ! @$status ) {
70   #    print "Adding freesidestatus column...\n";
71   #    $dbi->do("ALTER TABLE $table ADD COLUMN freesidestatus varchar(32)")
72   #      or die $dbi->errstr;
73   #  }
74   #  else {
75   #    print "freesidestatus column present\n";
76   #  }
77   # or if using a status_table:
78   #      CREATE TABLE FREESIDE_BILLING (
79   #        BILLING_ID BIGINT,
80   #        FREESIDESTATUS VARCHAR(32)
81   #      )
82
83   #my @cols = values %{ $args{column_map} };
84   my $sql = "SELECT * FROM $table "; # join(',', @cols). " FROM $table ".
85   $sql .=  'LEFT JOIN '. $args{status_table}.
86            ' USING ( '. $args{primary_key}. ' )'
87     if $args{status_table};
88   $sql .= ' WHERE freesidestatus IS NULL ';
89
90   #$sql .= ' LIMIT '. $opt{L} if $opt{L};
91   my $sth = $dbi->prepare($sql);
92   $sth->execute or die $sth->errstr. " executing $sql";
93   #MySQL-specific print "Importing ".$sth->rows." records...\n";
94
95   my $cdr_batch = new FS::cdr_batch({ 
96       'cdrbatch' => 'IVR-import-'. time2str('%Y/%m/%d-%T',time),
97     });
98   my $error = $cdr_batch->insert;
99   die $error if $error;
100   my $cdrbatchnum = $cdr_batch->cdrbatchnum;
101   my $imported = 0;
102
103   my $row;
104   while ( $row = $sth->fetchrow_hashref ) {
105
106     my %hash = ( 'cdrbatchnum' => $cdrbatchnum );
107     foreach my $field ( keys %{ $args{column_map} } ) {
108       my $col_or_coderef = $args{column_map}->{$field};
109       if ( ref($col_or_coderef) eq 'CODE' ) {
110         $hash{$field} = &{ $col_or_coderef }( $row );
111       } else {
112         $hash{$field} = $row->{ $col_or_coderef };
113       }
114       $hash{$field} = '' if $hash{$field} =~ /^\s+$/; #IVR (MSSQL?) bs
115     }
116     my $cdr = FS::cdr->new(\%hash);
117
118     $cdr->cdrtypenum($opt{c}) if $opt{c};
119
120     #print $row->{$pkey},"\n" if $opt{v};
121     my $error = $cdr->insert;
122
123     if ($error) {
124
125       #die $row->{$pkey} . ": failed import: $error\n";
126       print $row->{$pkey} . ": failed import: $error\n";
127
128     } else {
129
130       $imported++;
131
132       my $st_sql;
133       if ( $args{status_table} ) {
134
135         $st_sql = 
136           'INSERT INTO '. $args{status_table}. " ( $pkey, freesidestatus ) ".
137             " VALUES ( ?, 'done' )";
138
139       } else {
140
141         $st_sql = "UPDATE $table SET freesidestatus = 'done' WHERE $pkey = ?";
142
143       }
144
145       my $updated = $dbi->do($st_sql, undef, $row->{$pkey} );
146       #$updates += $updated;
147       die "failed to set status: ".$dbi->errstr."\n" unless $updated;
148
149     }
150
151     if ( $opt{L} && $imported >= $opt{L} ) {
152       $sth->finish;
153       last;
154     }
155
156   }
157   print "Done.\n";
158   print "Imported $imported CDRs.\n" if $imported;
159
160   $dbi->disconnect;
161
162 }
163
164 sub cli_usage {
165   #"Usage: \n  $0\n\t[ -H hostname ]\n\t-D database\n\t-U user\n\t-P password\n\tfreesideuser\n";
166   #"Usage: \n  $0\n\t-H hostname\n\t-D database\n\t-U user\n\t-P password\n\t[ -c cdrtypenum ]\n\tfreesideuser\n";
167   "Usage: \n  $0\n\t-H hostname\n\t[ -D database ]\n\t-U user\n\t-P password\n\t[ -c cdrtypenum ]\n\t[ -L num_cdrs_limit ]\n\tfreesideuser\n";
168 }
169
170 =head1 BUGS
171
172 Not everything has been refactored out of the various bin/cdr-*.import scripts,
173 let alone other places.
174
175 Sparse documentation.
176
177 =head1 SEE ALSO
178
179 L<FS::cdr>
180
181 =cut
182
183 1;