a97472e7a62cb0213b903d7d66af48991144a35b
[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 $table.* FROM $table "; # join(',', @cols). " FROM $table ".
85   $sql .=  'LEFT JOIN '. $args{status_table}.
86            " ON ( $table.$pkey = ". $args{status_table}. ".$pkey )"
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     my $pkey_value = $row->{$pkey};
121
122     #print "$pkey_value\n" if $opt{v};
123     my $error = $cdr->insert;
124
125     if ($error) {
126
127       #die "$pkey_value: failed import: $error\n";
128       print "$pkey_value: failed import: $error\n";
129
130     } else {
131
132       $imported++;
133
134       my $st_sql;
135       if ( $args{status_table} ) {
136
137         $st_sql = 
138           'INSERT INTO '. $args{status_table}. " ( $pkey, freesidestatus ) ".
139             " VALUES ( ?, 'done' )";
140
141       } else {
142
143         $st_sql = "UPDATE $table SET freesidestatus = 'done' WHERE $pkey = ?";
144
145       }
146
147       my $updated = $dbi->do($st_sql, undef, $pkey_value );
148       #$updates += $updated;
149       die "failed to set status: ".$dbi->errstr."\n" unless $updated;
150
151     }
152
153     if ( $opt{L} && $imported >= $opt{L} ) {
154       $sth->finish;
155       last;
156     }
157
158   }
159   print "Done.\n";
160   print "Imported $imported CDRs.\n" if $imported;
161
162   $dbi->disconnect;
163
164 }
165
166 sub cli_usage {
167   #"Usage: \n  $0\n\t[ -H hostname ]\n\t-D database\n\t-U user\n\t-P password\n\tfreesideuser\n";
168   #"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";
169   "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";
170 }
171
172 =head1 BUGS
173
174 Not everything has been refactored out of the various bin/cdr-*.import scripts,
175 let alone other places.
176
177 Sparse documentation.
178
179 =head1 SEE ALSO
180
181 L<FS::cdr>
182
183 =cut
184
185 1;