don't redirect to a GET with sensitive data, RT#26099
[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, processing-tiered, done
134
135 =item freesiderewritestatus - NULL, done, skipped
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
405   if ($opt{'inbound'}) {
406
407     my $term = $self->cdr_termination( 1 ); #1: inbound
408     my $error;
409     if ( $term ) {
410       warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
411       $error = $term->delete;
412       return $error if $error;
413     }
414     $term = FS::cdr_termination->new({
415         acctid      => $self->acctid,
416         termpart    => 1,
417         rated_price => $rated_price,
418         status      => $status,
419     });
420     $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
421     $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
422     $term->svcnum($svcnum) if $svcnum;
423     return $term->insert;
424
425   } else {
426
427     $self->freesidestatus($status);
428     $self->rated_price($rated_price);
429     $self->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
430     $self->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
431     $self->svcnum($svcnum) if $svcnum;
432     return $self->replace();
433
434   }
435 }
436
437 =item cdr_termination [ TERMPART ]
438
439 =cut
440
441 sub cdr_termination {
442   my $self = shift;
443
444   if ( scalar(@_) && $_[0] ) {
445     my $termpart = shift;
446
447     qsearchs('cdr_termination', { acctid   => $self->acctid,
448                                   termpart => $termpart,
449                                 }
450             );
451
452   } else {
453
454     qsearch('cdr_termination', { acctid => $self->acctid, } );
455
456   }
457
458 }
459
460 =item calldate_unix 
461
462 Parses the calldate in SQL string format and returns a UNIX timestamp.
463
464 =cut
465
466 sub calldate_unix {
467   str2time(shift->calldate);
468 }
469
470 =item startdate_sql
471
472 Parses the startdate in UNIX timestamp format and returns a string in SQL
473 format.
474
475 =cut
476
477 sub startdate_sql {
478   my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
479   $mon++;
480   $year += 1900;
481   "$year-$mon-$mday $hour:$min:$sec";
482 }
483
484 =item cdr_carrier
485
486 Returns the FS::cdr_carrier object associated with this CDR, or false if no
487 carrierid is defined.
488
489 =cut
490
491 my %carrier_cache = ();
492
493 sub cdr_carrier {
494   my $self = shift;
495   return '' unless $self->carrierid;
496   $carrier_cache{$self->carrierid} ||=
497     qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
498 }
499
500 =item carriername 
501
502 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
503 no FS::cdr_carrier object is assocated with this CDR.
504
505 =cut
506
507 sub carriername {
508   my $self = shift;
509   my $cdr_carrier = $self->cdr_carrier;
510   $cdr_carrier ? $cdr_carrier->carriername : '';
511 }
512
513 =item cdr_calltype
514
515 Returns the FS::cdr_calltype object associated with this CDR, or false if no
516 calltypenum is defined.
517
518 =cut
519
520 my %calltype_cache = ();
521
522 sub cdr_calltype {
523   my $self = shift;
524   return '' unless $self->calltypenum;
525   $calltype_cache{$self->calltypenum} ||=
526     qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
527 }
528
529 =item calltypename 
530
531 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
532 no FS::cdr_calltype object is assocated with this CDR.
533
534 =cut
535
536 sub calltypename {
537   my $self = shift;
538   my $cdr_calltype = $self->cdr_calltype;
539   $cdr_calltype ? $cdr_calltype->calltypename : '';
540 }
541
542 =item downstream_csv [ OPTION => VALUE, ... ]
543
544 =cut
545
546 my %export_names = (
547   'simple'  => {
548     'name'           => 'Simple',
549     'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
550   },
551   'simple2' => {
552     'name'           => 'Simple with source',
553     'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
554                        #"Date,Time,Name,Called From,Destination,Duration,Price",
555   },
556   'accountcode_simple' => {
557     'name'           => 'Simple with accountcode',
558     'invoice_header' => "Date,Time,Called From,Account,Duration,Price",
559   },
560   'basic' => {
561     'name'           => 'Basic',
562     'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
563   },
564   'default' => {
565     'name'           => 'Default',
566     'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
567   },
568   'source_default' => {
569     'name'           => 'Default with source',
570     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
571   },
572   'accountcode_default' => {
573     'name'           => 'Default plus accountcode',
574     'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
575   },
576   'description_default' => {
577     'name'           => 'Default with description field as destination',
578     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
579   },
580   'sum_duration' => {
581     'name'           => 'Summary (one line per service, with duration)',
582     'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
583   },
584   'sum_count' => {
585     'name'           => 'Summary (one line per service, with count)',
586     'invoice_header' => 'Caller,Rate,Messages,Price',
587   },
588 );
589
590 my %export_formats = ();
591 sub export_formats {
592   #my $self = shift;
593
594   return %export_formats if keys %export_formats;
595
596   my $conf = new FS::Conf;
597   my $date_format = $conf->config('date_format') || '%m/%d/%Y';
598
599   # call duration in the largest units that accurately reflect the  granularity
600   my $duration_sub = sub {
601     my($cdr, %opt) = @_;
602     my $sec = $opt{seconds} || $cdr->billsec;
603     if ( defined $opt{granularity} && 
604          $opt{granularity} == 0 ) { #per call
605       return '1 call';
606     }
607     elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
608       my $min = int($sec/60);
609       $min++ if $sec%60;
610       return $min.'m';
611     }
612     else { #anything else
613       return sprintf("%dm %ds", $sec/60, $sec%60);
614     }
615   };
616
617   my $price_sub = sub {
618     my ($cdr, %opt) = @_;
619     my $price;
620     if ( defined($opt{charge}) ) {
621       $price = $opt{charge};
622     }
623     elsif ( $opt{inbound} ) {
624       my $term = $cdr->cdr_termination(1); # 1 = inbound
625       $price = $term->rated_price if defined $term;
626     }
627     else {
628       $price = $cdr->rated_price;
629     }
630     length($price) ? ($opt{money_char} . $price) : '';
631   };
632
633   my $src_sub = sub { $_[0]->clid || $_[0]->src };
634
635   %export_formats = (
636     'simple' => [
637       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
638       sub { time2str('%r', shift->calldate_unix ) },   #TIME
639       'userfield',                                     #USER
640       'dst',                                           #NUMBER_DIALED
641       $duration_sub,                                   #DURATION
642       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
643       $price_sub,
644     ],
645     'simple2' => [
646       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
647       sub { time2str('%r', shift->calldate_unix ) },   #TIME
648       #'userfield',                                     #USER
649       $src_sub,                                           #called from
650       'dst',                                           #NUMBER_DIALED
651       $duration_sub,                                   #DURATION
652       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
653       $price_sub,
654     ],
655     'accountcode_simple' => [
656       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
657       sub { time2str('%r', shift->calldate_unix ) },   #TIME
658       $src_sub,                                           #called from
659       'accountcode',                                   #NUMBER_DIALED
660       $duration_sub,                                   #DURATION
661       $price_sub,
662     ],
663     'sum_duration' => [ 
664       # for summary formats, the CDR is a fictitious object containing the 
665       # total billsec and the phone number of the service
666       $src_sub,
667       sub { my($cdr, %opt) = @_; $opt{ratename} },
668       sub { my($cdr, %opt) = @_; $opt{count} },
669       sub { my($cdr, %opt) = @_; int($opt{seconds}/60).'m' },
670       $price_sub,
671     ],
672     'sum_count' => [
673       $src_sub,
674       sub { my($cdr, %opt) = @_; $opt{ratename} },
675       sub { my($cdr, %opt) = @_; $opt{count} },
676       $price_sub,
677     ],
678     'basic' => [
679       sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
680       'dst',
681       $duration_sub,
682       $price_sub,
683     ],
684     'default' => [
685
686       #DATE
687       sub { time2str($date_format, shift->calldate_unix ) },
688             # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
689
690       #TIME
691       sub { time2str('%r', shift->calldate_unix ) },
692             # 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
693
694       #DEST ("Number")
695       sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
696
697       #REGIONNAME ("Destination")
698       sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
699
700       #DURATION
701       $duration_sub,
702
703       #PRICE
704       $price_sub,
705     ],
706   );
707   $export_formats{'source_default'} = [ $src_sub, @{ $export_formats{'default'} }, ];
708   $export_formats{'accountcode_default'} =
709     [ @{ $export_formats{'default'} }[0,1],
710       'accountcode',
711       @{ $export_formats{'default'} }[2..5],
712     ];
713   my @default = @{ $export_formats{'default'} };
714   $export_formats{'description_default'} = 
715     [ $src_sub, @default[0..2], 
716       sub { my($cdr, %opt) = @_; $cdr->description },
717       @default[4,5] ];
718
719   return %export_formats;
720 }
721
722 =item downstream_csv OPTION => VALUE ...
723
724 Returns a string of formatted call details for display on an invoice.
725
726 Options:
727
728 format
729
730 charge - override the 'rated_price' field of the CDR
731
732 seconds - override the 'billsec' field of the CDR
733
734 count - number of usage events included in this record, for summary formats
735
736 ratename - name of the rate table used to rate this call
737
738 granularity
739
740 =cut
741
742 sub downstream_csv {
743   my( $self, %opt ) = @_;
744
745   my $format = $opt{'format'};
746   my %formats = $self->export_formats;
747   return "Unknown format $format" unless exists $formats{$format};
748
749   #my $conf = new FS::Conf;
750   #$opt{'money_char'} ||= $conf->config('money_char') || '$';
751   $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
752
753   eval "use Text::CSV_XS;";
754   die $@ if $@;
755   my $csv = new Text::CSV_XS;
756
757   my @columns =
758     map {
759           ref($_) ? &{$_}($self, %opt) : $self->$_();
760         }
761     @{ $formats{$format} };
762
763   return @columns if defined $opt{'keeparray'};
764
765   my $status = $csv->combine(@columns);
766   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
767     unless $status;
768
769   $csv->string;
770
771 }
772
773 =back
774
775 =head1 CLASS METHODS
776
777 =over 4
778
779 =item invoice_formats
780
781 Returns an ordered list of key value pairs containing invoice format names
782 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
783
784 =cut
785
786 sub invoice_formats {
787   map { ($_ => $export_names{$_}->{'name'}) }
788     grep { $export_names{$_}->{'invoice_header'} }
789     keys %export_names;
790 }
791
792 =item invoice_header FORMAT
793
794 Returns a scalar containing the CSV column header for invoice format FORMAT.
795
796 =cut
797
798 sub invoice_header {
799   my $format = shift;
800   $export_names{$format}->{'invoice_header'};
801 }
802
803 =item clear_status 
804
805 Clears cdr and any associated cdr_termination statuses - used for 
806 CDR reprocessing.
807
808 =cut
809
810 sub clear_status {
811   my $self = shift;
812
813   local $SIG{HUP} = 'IGNORE';
814   local $SIG{INT} = 'IGNORE';
815   local $SIG{QUIT} = 'IGNORE';
816   local $SIG{TERM} = 'IGNORE';
817   local $SIG{TSTP} = 'IGNORE';
818   local $SIG{PIPE} = 'IGNORE';
819
820   my $oldAutoCommit = $FS::UID::AutoCommit;
821   local $FS::UID::AutoCommit = 0;
822   my $dbh = dbh;
823
824   $self->freesidestatus('');
825   my $error = $self->replace;
826   if ( $error ) {
827     $dbh->rollback if $oldAutoCommit;
828     return $error;
829   } 
830
831   foreach my $cdr_termination ( $self->cdr_termination ) {
832       #$cdr_termination->status('');
833       #$error = $cdr_termination->replace;
834       $error = $cdr_termination->delete;
835       if ( $error ) {
836         $dbh->rollback if $oldAutoCommit;
837         return $error;
838       } 
839   }
840   
841   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
842
843   '';
844 }
845
846 =item import_formats
847
848 Returns an ordered list of key value pairs containing import format names
849 as keys (for use with batch_import) and "pretty" format names as values.
850
851 =cut
852
853 #false laziness w/part_pkg & part_export
854
855 my %cdr_info;
856 foreach my $INC ( @INC ) {
857   warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
858   foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
859     warn "attempting to load CDR format info from $file\n" if $DEBUG;
860     $file =~ /\/(\w+)\.pm$/ or do {
861       warn "unrecognized file in $INC/FS/cdr/: $file\n";
862       next;
863     };
864     my $mod = $1;
865     my $info = eval "use FS::cdr::$mod; ".
866                     "\\%FS::cdr::$mod\::info;";
867     if ( $@ ) {
868       die "error using FS::cdr::$mod (skipping): $@\n" if $@;
869       next;
870     }
871     unless ( keys %$info ) {
872       warn "no %info hash found in FS::cdr::$mod, skipping\n";
873       next;
874     }
875     warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
876     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
877       warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
878       next;
879     }
880     $cdr_info{$mod} = $info;
881   }
882 }
883
884 tie my %import_formats, 'Tie::IxHash',
885   map  { $_ => $cdr_info{$_}->{'name'} }
886   sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
887   grep { exists($cdr_info{$_}->{'import_fields'}) }
888   keys %cdr_info;
889
890 sub import_formats {
891   %import_formats;
892 }
893
894 sub _cdr_min_parser_maker {
895   my $field = shift;
896   my @fields = ref($field) ? @$field : ($field);
897   @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
898   return sub {
899     my( $cdr, $min ) = @_;
900     my $sec = eval { _cdr_min_parse($min) };
901     die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
902     $cdr->$_($sec) foreach @fields;
903   };
904 }
905
906 sub _cdr_min_parse {
907   my $min = shift;
908   sprintf('%.0f', $min * 60 );
909 }
910
911 sub _cdr_date_parser_maker {
912   my $field = shift;
913   my %options = @_;
914   my @fields = ref($field) ? @$field : ($field);
915   return sub {
916     my( $cdr, $datestring ) = @_;
917     my $unixdate = eval { _cdr_date_parse($datestring, %options) };
918     die "error parsing date for @fields from $datestring: $@\n" if $@;
919     $cdr->$_($unixdate) foreach @fields;
920   };
921 }
922
923 sub _cdr_date_parse {
924   my $date = shift;
925   my %options = @_;
926
927   return '' unless length($date); #that's okay, it becomes NULL
928   return '' if $date eq 'NA'; #sansay
929
930   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 ) {
931     my $time = str2time($date);
932     return $time if $time > 100000; #just in case
933   }
934
935   my($year, $mon, $day, $hour, $min, $sec);
936
937   #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
938   #taqua  #2007-10-31 08:57:24.113000000
939
940   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|$)/ ) {
941     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
942   } 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|$)/ ) {
943     # 8/26/2010 12:20:01
944     # optionally without seconds
945     ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
946     $sec = 0 if !defined($sec);
947   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
948     # broadsoft: 20081223201938.314
949     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
950   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
951     # Taqua OM:  20050422203450943
952     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
953   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
954     # WIP: 20100329121420
955     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
956   } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
957     # Telos
958     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
959     $options{gmt} = 1;
960   } else {
961      die "unparsable date: $date"; #maybe we shouldn't die...
962   }
963
964   return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
965             && $hour == 0 && $min == 0 && $sec == 0;
966
967   if ($options{gmt}) {
968     timegm($sec, $min, $hour, $day, $mon-1, $year);
969   } else {
970     timelocal($sec, $min, $hour, $day, $mon-1, $year);
971   }
972 }
973
974 =item batch_import HASHREF
975
976 Imports CDR records.  Available options are:
977
978 =over 4
979
980 =item file
981
982 Filename
983
984 =item format
985
986 =item params
987
988 Hash reference of preset fields, typically cdrbatch
989
990 =item empty_ok
991
992 Set true to prevent throwing an error on empty imports
993
994 =back
995
996 =cut
997
998 my %import_options = (
999   'table'         => 'cdr',
1000
1001   'batch_keycol'  => 'cdrbatchnum',
1002   'batch_table'   => 'cdr_batch',
1003   'batch_namecol' => 'cdrbatch',
1004
1005   'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
1006                      keys %cdr_info
1007                },
1008
1009                           #drop the || 'csv' to allow auto xls for csv types?
1010   'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
1011                           keys %cdr_info
1012                     },
1013
1014   'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
1015                             keys %cdr_info
1016                       },
1017
1018   'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
1019                               keys %cdr_info
1020                         },
1021
1022   'format_fixedlength_formats' =>
1023     { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
1024           keys %cdr_info
1025     },
1026
1027   'format_xml_formats' =>
1028     { map { $_ => $cdr_info{$_}->{'xml_format'}; }
1029           keys %cdr_info
1030     },
1031
1032   'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
1033                                   keys %cdr_info
1034                             },
1035 );
1036
1037 sub _import_options {
1038   \%import_options;
1039 }
1040
1041 sub batch_import {
1042   my $opt = shift;
1043
1044   my $iopt = _import_options;
1045   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
1046
1047   if ( defined $opt->{'cdrtypenum'} ) {
1048         $opt->{'preinsert_callback'} = sub {
1049                 my($record,$param) = (shift,shift);
1050                 $record->cdrtypenum($opt->{'cdrtypenum'});
1051                 '';
1052         };
1053   }
1054
1055   FS::Record::batch_import( $opt );
1056
1057 }
1058
1059 =item process_batch_import
1060
1061 =cut
1062
1063 sub process_batch_import {
1064   my $job = shift;
1065
1066   my $opt = _import_options;
1067 #  $opt->{'params'} = [ 'format', 'cdrbatch' ];
1068
1069   FS::Record::process_batch_import( $job, $opt, @_ );
1070
1071 }
1072 #  if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
1073 #    @columns = map { s/^ +//; $_; } @columns;
1074 #  }
1075
1076 # _ upgrade_data
1077 #
1078 # Used by FS::Upgrade to migrate to a new database.
1079
1080 sub _upgrade_data {
1081   my ($class, %opts) = @_;
1082
1083   warn "$me upgrading $class\n" if $DEBUG;
1084
1085   my $sth = dbh->prepare(
1086     'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
1087   ) or die dbh->errstr;
1088
1089   $sth->execute or die $sth->errstr;
1090
1091   my %cdrbatchnum = ();
1092   while (my $row = $sth->fetchrow_arrayref) {
1093
1094     my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
1095     unless ( $cdr_batch ) {
1096       $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
1097       my $error = $cdr_batch->insert;
1098       die $error if $error;
1099     }
1100
1101     $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
1102   }
1103
1104   $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1105
1106   foreach my $cdrbatch (keys %cdrbatchnum) {
1107     $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1108   }
1109
1110 }
1111
1112 =back
1113
1114 =head1 BUGS
1115
1116 =head1 SEE ALSO
1117
1118 L<FS::Record>, schema.html from the base documentation.
1119
1120 =cut
1121
1122 1;
1123