e7b6e6cd3fcd9d45fac2fc69cb9750af599d859d
[freeside.git] / FS / FS / cdr.pm
1 package FS::cdr;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG $me );
5 use Exporter;
6 use Tie::IxHash;
7 use Date::Parse;
8 use Date::Format;
9 use Time::Local;
10 use FS::UID qw( dbh );
11 use FS::Conf;
12 use FS::Record qw( qsearch qsearchs );
13 use FS::cdr_type;
14 use FS::cdr_calltype;
15 use FS::cdr_carrier;
16 use FS::cdr_batch;
17 use FS::cdr_termination;
18
19 @ISA = qw(FS::Record);
20 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
21
22 $DEBUG = 0;
23 $me = '[FS::cdr]';
24
25 =head1 NAME
26
27 FS::cdr - Object methods for cdr records
28
29 =head1 SYNOPSIS
30
31   use FS::cdr;
32
33   $record = new FS::cdr \%hash;
34   $record = new FS::cdr { 'column' => 'value' };
35
36   $error = $record->insert;
37
38   $error = $new_record->replace($old_record);
39
40   $error = $record->delete;
41
42   $error = $record->check;
43
44 =head1 DESCRIPTION
45
46 An FS::cdr object represents an Call Data Record, typically from a telephony
47 system or provider of some sort.  FS::cdr inherits from FS::Record.  The
48 following fields are currently supported:
49
50 =over 4
51
52 =item acctid - primary key
53
54 =item calldate - Call timestamp (SQL timestamp)
55
56 =item clid - Caller*ID with text
57
58 =item src - Caller*ID number / Source number
59
60 =item dst - Destination extension
61
62 =item dcontext - Destination context
63
64 =item channel - Channel used
65
66 =item dstchannel - Destination channel if appropriate
67
68 =item lastapp - Last application if appropriate
69
70 =item lastdata - Last application data
71
72 =item startdate - Start of call (UNIX-style integer timestamp)
73
74 =item answerdate - Answer time of call (UNIX-style integer timestamp)
75
76 =item enddate - End time of call (UNIX-style integer timestamp)
77
78 =item duration - Total time in system, in seconds
79
80 =item billsec - Total time call is up, in seconds
81
82 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY 
83
84 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode. 
85
86 =cut
87
88   #ignore the "omit" and "documentation" AMAs??
89   #AMA = Automated Message Accounting. 
90   #default: Sets the system default. 
91   #omit: Do not record calls. 
92   #billing: Mark the entry for billing 
93   #documentation: Mark the entry for documentation.
94
95 =item accountcode - CDR account number to use: account
96
97 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
98
99 =item userfield - CDR user-defined field
100
101 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
102
103 =item charged_party - Service number to be billed
104
105 =item upstream_currency - Wholesale currency from upstream
106
107 =item upstream_price - Wholesale price from upstream
108
109 =item upstream_rateplanid - Upstream rate plan ID
110
111 =item rated_price - Rated (or re-rated) price
112
113 =item distance - km (need units field?)
114
115 =item islocal - Local - 1, Non Local = 0
116
117 =item calltypenum - Type of call - see L<FS::cdr_calltype>
118
119 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
120
121 =item quantity - Number of items (cdr_type 7&8 only)
122
123 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>) 
124
125 =cut
126
127 #Telstra =1, Optus = 2, RSL COM = 3
128
129 =item upstream_rateid - Upstream Rate ID
130
131 =item svcnum - Link to customer service (see L<FS::cust_svc>)
132
133 =item freesidestatus - NULL, done (or something)
134
135 =item freesiderewritestatus - NULL, done (or something)
136
137 =item cdrbatch
138
139 =back
140
141 =head1 METHODS
142
143 =over 4
144
145 =item new HASHREF
146
147 Creates a new CDR.  To add the CDR to the database, see L<"insert">.
148
149 Note that this stores the hash reference, not a distinct copy of the hash it
150 points to.  You can ask the object for a copy with the I<hash> method.
151
152 =cut
153
154 # the new method can be inherited from FS::Record, if a table method is defined
155
156 sub table { 'cdr'; }
157
158 sub table_info {
159   {
160     'fields' => {
161 #XXX fill in some (more) nice names
162         #'acctid'                => '',
163         'calldate'              => 'Call date',
164         'clid'                  => 'Caller ID',
165         'src'                   => 'Source',
166         'dst'                   => 'Destination',
167         'dcontext'              => 'Dest. context',
168         'channel'               => 'Channel',
169         'dstchannel'            => 'Destination channel',
170         #'lastapp'               => '',
171         #'lastdata'              => '',
172         'startdate'             => 'Start date',
173         'answerdate'            => 'Answer date',
174         'enddate'               => 'End date',
175         'duration'              => 'Duration',
176         'billsec'               => 'Billable seconds',
177         'disposition'           => 'Disposition',
178         'amaflags'              => 'AMA flags',
179         'accountcode'           => 'Account code',
180         #'uniqueid'              => '',
181         'userfield'             => 'User field',
182         #'cdrtypenum'            => '',
183         'charged_party'         => 'Charged party',
184         #'upstream_currency'     => '',
185         'upstream_price'        => 'Upstream price',
186         #'upstream_rateplanid'   => '',
187         #'ratedetailnum'         => '',
188         'rated_price'           => 'Rated price',
189         #'distance'              => '',
190         #'islocal'               => '',
191         #'calltypenum'           => '',
192         #'description'           => '',
193         #'quantity'              => '',
194         'carrierid'             => 'Carrier ID',
195         #'upstream_rateid'       => '',
196         'svcnum'                => 'Freeside service',
197         'freesidestatus'        => 'Freeside status',
198         'freesiderewritestatus' => 'Freeside rewrite status',
199         'cdrbatch'              => 'Legacy batch',
200         'cdrbatchnum'           => 'Batch',
201     },
202
203   };
204
205 }
206
207 =item insert
208
209 Adds this record to the database.  If there is an error, returns the error,
210 otherwise returns false.
211
212 =cut
213
214 # the insert method can be inherited from FS::Record
215
216 =item delete
217
218 Delete this record from the database.
219
220 =cut
221
222 # the delete method can be inherited from FS::Record
223
224 =item replace OLD_RECORD
225
226 Replaces the OLD_RECORD with this one in the database.  If there is an error,
227 returns the error, otherwise returns false.
228
229 =cut
230
231 # the replace method can be inherited from FS::Record
232
233 =item check
234
235 Checks all fields to make sure this is a valid CDR.  If there is
236 an error, returns the error, otherwise returns false.  Called by the insert
237 and replace methods.
238
239 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
240 to process them as quickly as possible, so we allow the database to check most
241 of the data.
242
243 =cut
244
245 sub check {
246   my $self = shift;
247
248 # we don't want to "reject" a CDR like other sorts of input...
249 #  my $error = 
250 #    $self->ut_numbern('acctid')
251 ##    || $self->ut_('calldate')
252 #    || $self->ut_text('clid')
253 #    || $self->ut_text('src')
254 #    || $self->ut_text('dst')
255 #    || $self->ut_text('dcontext')
256 #    || $self->ut_text('channel')
257 #    || $self->ut_text('dstchannel')
258 #    || $self->ut_text('lastapp')
259 #    || $self->ut_text('lastdata')
260 #    || $self->ut_numbern('startdate')
261 #    || $self->ut_numbern('answerdate')
262 #    || $self->ut_numbern('enddate')
263 #    || $self->ut_number('duration')
264 #    || $self->ut_number('billsec')
265 #    || $self->ut_text('disposition')
266 #    || $self->ut_number('amaflags')
267 #    || $self->ut_text('accountcode')
268 #    || $self->ut_text('uniqueid')
269 #    || $self->ut_text('userfield')
270 #    || $self->ut_numbern('cdrtypenum')
271 #    || $self->ut_textn('charged_party')
272 ##    || $self->ut_n('upstream_currency')
273 ##    || $self->ut_n('upstream_price')
274 #    || $self->ut_numbern('upstream_rateplanid')
275 ##    || $self->ut_n('distance')
276 #    || $self->ut_numbern('islocal')
277 #    || $self->ut_numbern('calltypenum')
278 #    || $self->ut_textn('description')
279 #    || $self->ut_numbern('quantity')
280 #    || $self->ut_numbern('carrierid')
281 #    || $self->ut_numbern('upstream_rateid')
282 #    || $self->ut_numbern('svcnum')
283 #    || $self->ut_textn('freesidestatus')
284 #    || $self->ut_textn('freesiderewritestatus')
285 #  ;
286 #  return $error if $error;
287
288   for my $f ( grep { $self->$_ =~ /\D/ } qw(startdate answerdate enddate)){
289     $self->$f( str2time($self->$f) );
290   }
291
292   $self->calldate( $self->startdate_sql )
293     if !$self->calldate && $self->startdate;
294
295   #was just for $format eq 'taqua' but can't see the harm... add something to
296   #disable if it becomes a problem
297   if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
298     $self->duration( $self->enddate - $self->startdate  );
299   }
300   if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
301     $self->billsec(  $self->enddate - $self->answerdate );
302   } 
303
304   $self->set_charged_party;
305
306   #check the foreign keys even?
307   #do we want to outright *reject* the CDR?
308   my $error =
309        $self->ut_numbern('acctid')
310
311   #add a config option to turn these back on if someone needs 'em
312   #
313   #  #Usage = 1, S&E = 7, OC&C = 8
314   #  || $self->ut_foreign_keyn('cdrtypenum',  'cdr_type',     'cdrtypenum' )
315   #
316   #  #the big list in appendix 2
317   #  || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
318   #
319   #  # Telstra =1, Optus = 2, RSL COM = 3
320   #  || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
321   ;
322   return $error if $error;
323
324   $self->SUPER::check;
325 }
326
327 =item is_tollfree [ COLUMN ]
328
329 Returns true when the cdr represents a toll free number and false otherwise.
330
331 By default, inspects the dst field, but an optional column name can be passed
332 to inspect other field.
333
334 =cut
335
336 sub is_tollfree {
337   my $self = shift;
338   my $field = scalar(@_) ? shift : 'dst';
339   ( $self->$field() =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
340 }
341
342 =item set_charged_party
343
344 If the charged_party field is already set, does nothing.  Otherwise:
345
346 If the cdr-charged_party-accountcode config option is enabled, sets the
347 charged_party to the accountcode.
348
349 Otherwise sets the charged_party normally: to the src field in most cases,
350 or to the dst field if it is a toll free number.
351
352 =cut
353
354 sub set_charged_party {
355   my $self = shift;
356
357   my $conf = new FS::Conf;
358
359   unless ( $self->charged_party ) {
360
361     if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
362
363       my $charged_party = $self->accountcode;
364       $charged_party =~ s/^0+//
365         if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
366       $self->charged_party( $charged_party );
367
368     } elsif ( $conf->exists('cdr-charged_party-field') ) {
369
370       my $field = $conf->config('cdr-charged_party-field');
371       $self->charged_party( $self->$field() );
372
373     } else {
374
375       if ( $self->is_tollfree ) {
376         $self->charged_party($self->dst);
377       } else {
378         $self->charged_party($self->src);
379       }
380
381     }
382
383   }
384
385 #  my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
386 #  my $prefix_len = length($prefix);
387 #  my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
388 #
389 #  $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
390 #    if $prefix_len && $trunc_len
391 #    && substr($self->charged_party, 0, $prefix_len) eq $prefix;
392
393 }
394
395 =item set_status_and_rated_price STATUS [ RATED_PRICE [ SVCNUM ] ]
396
397 Sets the status to the provided string.  If there is an error, returns the
398 error, otherwise returns false.
399
400 =cut
401
402 sub set_status_and_rated_price {
403   my($self, $status, $rated_price, $svcnum, %opt) = @_;
404   if($opt{'inbound'}) {
405     my $term = qsearchs('cdr_termination', {
406         acctid   => $self->acctid, 
407         termpart => 1 # inbound
408     });
409     my $error;
410     if($term) {
411       warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
412       $error = $term->delete;
413       return $error if $error;
414     }
415     $term = FS::cdr_termination->new({
416         acctid      => $self->acctid,
417         termpart    => 1,
418         rated_price => $rated_price,
419         status      => $status,
420         svcnum      => $svcnum,
421     });
422     return $term->insert;
423   }
424   else {
425     $self->freesidestatus($status);
426     $self->rated_price($rated_price);
427     $self->svcnum($svcnum) if $svcnum;
428     return $self->replace();
429   }
430 }
431
432 =item calldate_unix 
433
434 Parses the calldate in SQL string format and returns a UNIX timestamp.
435
436 =cut
437
438 sub calldate_unix {
439   str2time(shift->calldate);
440 }
441
442 =item startdate_sql
443
444 Parses the startdate in UNIX timestamp format and returns a string in SQL
445 format.
446
447 =cut
448
449 sub startdate_sql {
450   my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
451   $mon++;
452   $year += 1900;
453   "$year-$mon-$mday $hour:$min:$sec";
454 }
455
456 =item cdr_carrier
457
458 Returns the FS::cdr_carrier object associated with this CDR, or false if no
459 carrierid is defined.
460
461 =cut
462
463 my %carrier_cache = ();
464
465 sub cdr_carrier {
466   my $self = shift;
467   return '' unless $self->carrierid;
468   $carrier_cache{$self->carrierid} ||=
469     qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
470 }
471
472 =item carriername 
473
474 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
475 no FS::cdr_carrier object is assocated with this CDR.
476
477 =cut
478
479 sub carriername {
480   my $self = shift;
481   my $cdr_carrier = $self->cdr_carrier;
482   $cdr_carrier ? $cdr_carrier->carriername : '';
483 }
484
485 =item cdr_calltype
486
487 Returns the FS::cdr_calltype object associated with this CDR, or false if no
488 calltypenum is defined.
489
490 =cut
491
492 my %calltype_cache = ();
493
494 sub cdr_calltype {
495   my $self = shift;
496   return '' unless $self->calltypenum;
497   $calltype_cache{$self->calltypenum} ||=
498     qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
499 }
500
501 =item calltypename 
502
503 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
504 no FS::cdr_calltype object is assocated with this CDR.
505
506 =cut
507
508 sub calltypename {
509   my $self = shift;
510   my $cdr_calltype = $self->cdr_calltype;
511   $cdr_calltype ? $cdr_calltype->calltypename : '';
512 }
513
514 =item downstream_csv [ OPTION => VALUE, ... ]
515
516 =cut
517
518 my %export_names = (
519   'simple'  => {
520     'name'           => 'Simple',
521     'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
522   },
523   'simple2' => {
524     'name'           => 'Simple with source',
525     'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
526                        #"Date,Time,Name,Called From,Destination,Duration,Price",
527   },
528   'basic' => {
529     'name'           => 'Basic',
530     'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
531   },
532   'default' => {
533     'name'           => 'Default',
534     'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
535   },
536   'source_default' => {
537     'name'           => 'Default with source',
538     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
539   },
540   'accountcode_default' => {
541     'name'           => 'Default plus accountcode',
542     'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
543   },
544   'description_default' => {
545     'name'           => 'Default with description field as destination',
546     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
547   },
548 );
549
550 my %export_formats = ();
551 sub export_formats {
552   #my $self = shift;
553
554   return %export_formats if keys %export_formats;
555
556   my $conf = new FS::Conf;
557   my $date_format = $conf->config('date_format') || '%m/%d/%Y';
558
559   # call duration in the largest units that accurately reflect the  granularity
560   my $duration_sub = sub {
561     my($cdr, %opt) = @_;
562     my $sec = $opt{seconds} || $cdr->billsec;
563     if ( defined $opt{granularity} && 
564          $opt{granularity} == 0 ) { #per call
565       return '1 call';
566     }
567     elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
568       my $min = int($sec/60);
569       $min++ if $sec%60;
570       return $min.'m';
571     }
572     else { #anything else
573       return sprintf("%dm %ds", $sec/60, $sec%60);
574     }
575   };
576
577   %export_formats = (
578     'simple' => [
579       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
580       sub { time2str('%r', shift->calldate_unix ) },   #TIME
581       'userfield',                                     #USER
582       'dst',                                           #NUMBER_DIALED
583       $duration_sub,                                   #DURATION
584       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
585       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
586     ],
587     'simple2' => [
588       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
589       sub { time2str('%r', shift->calldate_unix ) },   #TIME
590       #'userfield',                                     #USER
591       'src',                                           #called from
592       'dst',                                           #NUMBER_DIALED
593       $duration_sub,                                   #DURATION
594       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
595       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
596     ],
597     'basic' => [
598       sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
599       'dst',
600       $duration_sub,
601       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
602     ],
603     'default' => [
604
605       #DATE
606       sub { time2str($date_format, shift->calldate_unix ) },
607             # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
608
609       #TIME
610       sub { time2str('%r', shift->calldate_unix ) },
611             # time2str("%c", $cdr->calldate_unix),  #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
612
613       #DEST ("Number")
614       sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
615
616       #REGIONNAME ("Destination")
617       sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
618
619       #DURATION
620       $duration_sub,
621
622       #PRICE
623       sub { my($cdr, %opt) = @_; 
624         $opt{charge} = '0.00' unless defined $opt{charge};
625         $opt{money_char}.$opt{charge}; 
626       },
627
628     ],
629   );
630   $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
631   $export_formats{'accountcode_default'} =
632     [ @{ $export_formats{'default'} }[0,1],
633       'accountcode',
634       @{ $export_formats{'default'} }[2..5],
635     ];
636   my @default = @{ $export_formats{'default'} };
637   $export_formats{'description_default'} = 
638     [ 'src', @default[0..2], 
639       sub { my($cdr, %opt) = @_; $cdr->description },
640       @default[4,5] ];
641
642   return %export_formats;
643 }
644
645 sub downstream_csv {
646   my( $self, %opt ) = @_;
647
648   my $format = $opt{'format'};
649   my %formats = $self->export_formats;
650   return "Unknown format $format" unless exists $formats{$format};
651
652   #my $conf = new FS::Conf;
653   #$opt{'money_char'} ||= $conf->config('money_char') || '$';
654   $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
655
656   eval "use Text::CSV_XS;";
657   die $@ if $@;
658   my $csv = new Text::CSV_XS;
659
660   my @columns =
661     map {
662           ref($_) ? &{$_}($self, %opt) : $self->$_();
663         }
664     @{ $formats{$format} };
665
666   return @columns if defined $opt{'keeparray'};
667
668   my $status = $csv->combine(@columns);
669   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
670     unless $status;
671
672   $csv->string;
673
674 }
675
676 =back
677
678 =head1 CLASS METHODS
679
680 =over 4
681
682 =item invoice_formats
683
684 Returns an ordered list of key value pairs containing invoice format names
685 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
686
687 =cut
688
689 sub invoice_formats {
690   map { ($_ => $export_names{$_}->{'name'}) }
691     grep { $export_names{$_}->{'invoice_header'} }
692     keys %export_names;
693 }
694
695 =item invoice_header FORMAT
696
697 Returns a scalar containing the CSV column header for invoice format FORMAT.
698
699 =cut
700
701 sub invoice_header {
702   my $format = shift;
703   $export_names{$format}->{'invoice_header'};
704 }
705
706 =item clear_status 
707
708 Clears cdr and any associated cdr_termination statuses - used for 
709 CDR reprocessing.
710
711 =cut
712
713 sub clear_status {
714   my $self = shift;
715
716   local $SIG{HUP} = 'IGNORE';
717   local $SIG{INT} = 'IGNORE';
718   local $SIG{QUIT} = 'IGNORE';
719   local $SIG{TERM} = 'IGNORE';
720   local $SIG{TSTP} = 'IGNORE';
721   local $SIG{PIPE} = 'IGNORE';
722
723   my $oldAutoCommit = $FS::UID::AutoCommit;
724   local $FS::UID::AutoCommit = 0;
725   my $dbh = dbh;
726
727   $self->freesidestatus('');
728   my $error = $self->replace;
729   if ( $error ) {
730     $dbh->rollback if $oldAutoCommit;
731     return $error;
732   } 
733
734   my @cdr_termination = qsearch('cdr_termination', 
735                                 { 'acctid' => $self->acctid } );
736   foreach my $cdr_termination ( @cdr_termination ) {
737       $cdr_termination->status('');
738       $error = $cdr_termination->replace;
739       if ( $error ) {
740         $dbh->rollback if $oldAutoCommit;
741         return $error;
742       } 
743   }
744   
745   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
746
747   '';
748 }
749
750 =item import_formats
751
752 Returns an ordered list of key value pairs containing import format names
753 as keys (for use with batch_import) and "pretty" format names as values.
754
755 =cut
756
757 #false laziness w/part_pkg & part_export
758
759 my %cdr_info;
760 foreach my $INC ( @INC ) {
761   warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
762   foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
763     warn "attempting to load CDR format info from $file\n" if $DEBUG;
764     $file =~ /\/(\w+)\.pm$/ or do {
765       warn "unrecognized file in $INC/FS/cdr/: $file\n";
766       next;
767     };
768     my $mod = $1;
769     my $info = eval "use FS::cdr::$mod; ".
770                     "\\%FS::cdr::$mod\::info;";
771     if ( $@ ) {
772       die "error using FS::cdr::$mod (skipping): $@\n" if $@;
773       next;
774     }
775     unless ( keys %$info ) {
776       warn "no %info hash found in FS::cdr::$mod, skipping\n";
777       next;
778     }
779     warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
780     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
781       warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
782       next;
783     }
784     $cdr_info{$mod} = $info;
785   }
786 }
787
788 tie my %import_formats, 'Tie::IxHash',
789   map  { $_ => $cdr_info{$_}->{'name'} }
790   sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
791   grep { exists($cdr_info{$_}->{'import_fields'}) }
792   keys %cdr_info;
793
794 sub import_formats {
795   %import_formats;
796 }
797
798 sub _cdr_min_parser_maker {
799   my $field = shift;
800   my @fields = ref($field) ? @$field : ($field);
801   @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
802   return sub {
803     my( $cdr, $min ) = @_;
804     my $sec = eval { _cdr_min_parse($min) };
805     die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
806     $cdr->$_($sec) foreach @fields;
807   };
808 }
809
810 sub _cdr_min_parse {
811   my $min = shift;
812   sprintf('%.0f', $min * 60 );
813 }
814
815 sub _cdr_date_parser_maker {
816   my $field = shift;
817   my %options = @_;
818   my @fields = ref($field) ? @$field : ($field);
819   return sub {
820     my( $cdr, $datestring ) = @_;
821     my $unixdate = eval { _cdr_date_parse($datestring, %options) };
822     die "error parsing date for @fields from $datestring: $@\n" if $@;
823     $cdr->$_($unixdate) foreach @fields;
824   };
825 }
826
827 sub _cdr_date_parse {
828   my $date = shift;
829   my %options = @_;
830
831   return '' unless length($date); #that's okay, it becomes NULL
832   return '' if $date eq 'NA'; #sansay
833
834   if ( $date =~ /^([a-z]{3})\s+([a-z]{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s+(\d{4})$/i && $7 > 1970 ) {
835     my $time = str2time($date);
836     return $time if $time > 100000; #just in case
837   }
838
839   my($year, $mon, $day, $hour, $min, $sec);
840
841   #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
842   #taqua  #2007-10-31 08:57:24.113000000
843
844   if ( $date =~ /^\s*(\d{4})\D(\d{1,2})\D(\d{1,2})\D+(\d{1,2})\D(\d{1,2})\D(\d{1,2})(\D|$)/ ) {
845     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
846   } elsif ( $date  =~ /^\s*(\d{1,2})\D(\d{1,2})\D(\d{4})\s+(\d{1,2})\D(\d{1,2})(?:\D(\d{1,2}))?(\D|$)/ ) {
847     # 8/26/2010 12:20:01
848     # optionally without seconds
849     ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
850     $sec = 0 if !defined($sec);
851   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
852     # broadsoft: 20081223201938.314
853     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
854   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
855     # Taqua OM:  20050422203450943
856     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
857   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
858     # WIP: 20100329121420
859     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
860   } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
861     # Telos
862     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
863     $options{gmt} = 1;
864   } else {
865      die "unparsable date: $date"; #maybe we shouldn't die...
866   }
867
868   return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
869             && $hour == 0 && $min == 0 && $sec == 0;
870
871   if ($options{gmt}) {
872     timegm($sec, $min, $hour, $day, $mon-1, $year);
873   } else {
874     timelocal($sec, $min, $hour, $day, $mon-1, $year);
875   }
876 }
877
878 =item batch_import HASHREF
879
880 Imports CDR records.  Available options are:
881
882 =over 4
883
884 =item file
885
886 Filename
887
888 =item format
889
890 =item params
891
892 Hash reference of preset fields, typically cdrbatch
893
894 =item empty_ok
895
896 Set true to prevent throwing an error on empty imports
897
898 =back
899
900 =cut
901
902 my %import_options = (
903   'table'         => 'cdr',
904
905   'batch_keycol'  => 'cdrbatchnum',
906   'batch_table'   => 'cdr_batch',
907   'batch_namecol' => 'cdrbatch',
908
909   'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
910                      keys %cdr_info
911                },
912
913                           #drop the || 'csv' to allow auto xls for csv types?
914   'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
915                           keys %cdr_info
916                     },
917
918   'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
919                             keys %cdr_info
920                       },
921
922   'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
923                               keys %cdr_info
924                         },
925
926   'format_fixedlength_formats' =>
927     { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
928           keys %cdr_info
929     },
930
931   'format_xml_formats' =>
932     { map { $_ => $cdr_info{$_}->{'xml_format'}; }
933           keys %cdr_info
934     },
935
936   'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
937                                   keys %cdr_info
938                             },
939 );
940
941 sub _import_options {
942   \%import_options;
943 }
944
945 sub batch_import {
946   my $opt = shift;
947
948   my $iopt = _import_options;
949   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
950
951   FS::Record::batch_import( $opt );
952
953 }
954
955 =item process_batch_import
956
957 =cut
958
959 sub process_batch_import {
960   my $job = shift;
961
962   my $opt = _import_options;
963 #  $opt->{'params'} = [ 'format', 'cdrbatch' ];
964
965   FS::Record::process_batch_import( $job, $opt, @_ );
966
967 }
968 #  if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
969 #    @columns = map { s/^ +//; $_; } @columns;
970 #  }
971
972 # _ upgrade_data
973 #
974 # Used by FS::Upgrade to migrate to a new database.
975
976 sub _upgrade_data {
977   my ($class, %opts) = @_;
978
979   warn "$me upgrading $class\n" if $DEBUG;
980
981   my $sth = dbh->prepare(
982     'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
983   ) or die dbh->errstr;
984
985   $sth->execute or die $sth->errstr;
986
987   my %cdrbatchnum = ();
988   while (my $row = $sth->fetchrow_arrayref) {
989
990     my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
991     unless ( $cdr_batch ) {
992       $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
993       my $error = $cdr_batch->insert;
994       die $error if $error;
995     }
996
997     $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
998   }
999
1000   $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1001
1002   foreach my $cdrbatch (keys %cdrbatchnum) {
1003     $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1004   }
1005
1006 }
1007
1008 =back
1009
1010 =head1 BUGS
1011
1012 =head1 SEE ALSO
1013
1014 L<FS::Record>, schema.html from the base documentation.
1015
1016 =cut
1017
1018 1;
1019