checkpoint taqua
[freeside.git] / FS / FS / cdr.pm
1 package FS::cdr;
2
3 use strict;
4 use vars qw( @ISA );
5 use Date::Parse;
6 use Date::Format;
7 use Time::Local;
8 use FS::UID qw( dbh );
9 use FS::Record qw( qsearch qsearchs );
10 use FS::cdr_type;
11 use FS::cdr_calltype;
12 use FS::cdr_carrier;
13 use FS::cdr_upstream_rate;
14
15 @ISA = qw(FS::Record);
16
17 =head1 NAME
18
19 FS::cdr - Object methods for cdr records
20
21 =head1 SYNOPSIS
22
23   use FS::cdr;
24
25   $record = new FS::cdr \%hash;
26   $record = new FS::cdr { 'column' => 'value' };
27
28   $error = $record->insert;
29
30   $error = $new_record->replace($old_record);
31
32   $error = $record->delete;
33
34   $error = $record->check;
35
36 =head1 DESCRIPTION
37
38 An FS::cdr object represents an Call Data Record, typically from a telephony
39 system or provider of some sort.  FS::cdr inherits from FS::Record.  The
40 following fields are currently supported:
41
42 =over 4
43
44 =item acctid - primary key
45
46 =item calldate - Call timestamp (SQL timestamp)
47
48 =item clid - Caller*ID with text
49
50 =item src - Caller*ID number / Source number
51
52 =item dst - Destination extension
53
54 =item dcontext - Destination context
55
56 =item channel - Channel used
57
58 =item dstchannel - Destination channel if appropriate
59
60 =item lastapp - Last application if appropriate
61
62 =item lastdata - Last application data
63
64 =item startdate - Start of call (UNIX-style integer timestamp)
65
66 =item answerdate - Answer time of call (UNIX-style integer timestamp)
67
68 =item enddate - End time of call (UNIX-style integer timestamp)
69
70 =item duration - Total time in system, in seconds
71
72 =item billsec - Total time call is up, in seconds
73
74 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY 
75
76 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode. 
77
78 =cut
79
80   #ignore the "omit" and "documentation" AMAs??
81   #AMA = Automated Message Accounting. 
82   #default: Sets the system default. 
83   #omit: Do not record calls. 
84   #billing: Mark the entry for billing 
85   #documentation: Mark the entry for documentation.
86
87 =item accountcode - CDR account number to use: account
88
89 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
90
91 =item userfield - CDR user-defined field
92
93 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
94
95 =item charged_party - Service number to be billed
96
97 =item upstream_currency - Wholesale currency from upstream
98
99 =item upstream_price - Wholesale price from upstream
100
101 =item upstream_rateplanid - Upstream rate plan ID
102
103 =item rated_price - Rated (or re-rated) price
104
105 =item distance - km (need units field?)
106
107 =item islocal - Local - 1, Non Local = 0
108
109 =item calltypenum - Type of call - see L<FS::cdr_calltype>
110
111 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
112
113 =item quantity - Number of items (cdr_type 7&8 only)
114
115 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>) 
116
117 =cut
118
119 #Telstra =1, Optus = 2, RSL COM = 3
120
121 =item upstream_rateid - Upstream Rate ID
122
123 =item svcnum - Link to customer service (see L<FS::cust_svc>)
124
125 =item freesidestatus - NULL, done (or something)
126
127 =back
128
129 =head1 METHODS
130
131 =over 4
132
133 =item new HASHREF
134
135 Creates a new CDR.  To add the CDR to the database, see L<"insert">.
136
137 Note that this stores the hash reference, not a distinct copy of the hash it
138 points to.  You can ask the object for a copy with the I<hash> method.
139
140 =cut
141
142 # the new method can be inherited from FS::Record, if a table method is defined
143
144 sub table { 'cdr'; }
145
146 =item insert
147
148 Adds this record to the database.  If there is an error, returns the error,
149 otherwise returns false.
150
151 =cut
152
153 # the insert method can be inherited from FS::Record
154
155 =item delete
156
157 Delete this record from the database.
158
159 =cut
160
161 # the delete method can be inherited from FS::Record
162
163 =item replace OLD_RECORD
164
165 Replaces the OLD_RECORD with this one in the database.  If there is an error,
166 returns the error, otherwise returns false.
167
168 =cut
169
170 # the replace method can be inherited from FS::Record
171
172 =item check
173
174 Checks all fields to make sure this is a valid CDR.  If there is
175 an error, returns the error, otherwise returns false.  Called by the insert
176 and replace methods.
177
178 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
179 to process them as quickly as possible, so we allow the database to check most
180 of the data.
181
182 =cut
183
184 sub check {
185   my $self = shift;
186
187 # we don't want to "reject" a CDR like other sorts of input...
188 #  my $error = 
189 #    $self->ut_numbern('acctid')
190 ##    || $self->ut_('calldate')
191 #    || $self->ut_text('clid')
192 #    || $self->ut_text('src')
193 #    || $self->ut_text('dst')
194 #    || $self->ut_text('dcontext')
195 #    || $self->ut_text('channel')
196 #    || $self->ut_text('dstchannel')
197 #    || $self->ut_text('lastapp')
198 #    || $self->ut_text('lastdata')
199 #    || $self->ut_numbern('startdate')
200 #    || $self->ut_numbern('answerdate')
201 #    || $self->ut_numbern('enddate')
202 #    || $self->ut_number('duration')
203 #    || $self->ut_number('billsec')
204 #    || $self->ut_text('disposition')
205 #    || $self->ut_number('amaflags')
206 #    || $self->ut_text('accountcode')
207 #    || $self->ut_text('uniqueid')
208 #    || $self->ut_text('userfield')
209 #    || $self->ut_numbern('cdrtypenum')
210 #    || $self->ut_textn('charged_party')
211 ##    || $self->ut_n('upstream_currency')
212 ##    || $self->ut_n('upstream_price')
213 #    || $self->ut_numbern('upstream_rateplanid')
214 ##    || $self->ut_n('distance')
215 #    || $self->ut_numbern('islocal')
216 #    || $self->ut_numbern('calltypenum')
217 #    || $self->ut_textn('description')
218 #    || $self->ut_numbern('quantity')
219 #    || $self->ut_numbern('carrierid')
220 #    || $self->ut_numbern('upstream_rateid')
221 #    || $self->ut_numbern('svcnum')
222 #    || $self->ut_textn('freesidestatus')
223 #  ;
224 #  return $error if $error;
225
226   $self->calldate( $self->startdate_sql )
227     if !$self->calldate && $self->startdate;
228
229   unless ( $self->charged_party ) {
230     if ( $self->dst =~ /^(\+?1)?8[02-8]{2}/ ) {
231       $self->charged_party($self->dst);
232     } else {
233       $self->charged_party($self->src);
234     }
235   }
236
237   #check the foreign keys even?
238   #do we want to outright *reject* the CDR?
239   my $error =
240        $self->ut_numbern('acctid')
241
242     #Usage = 1, S&E = 7, OC&C = 8
243     || $self->ut_foreign_keyn('cdrtypenum',  'cdr_type',     'cdrtypenum' )
244
245     #the big list in appendix 2
246     || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
247
248     # Telstra =1, Optus = 2, RSL COM = 3
249     || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
250   ;
251   return $error if $error;
252
253   $self->SUPER::check;
254 }
255
256 =item set_status_and_rated_price STATUS [ RATED_PRICE ]
257
258 Sets the status to the provided string.  If there is an error, returns the
259 error, otherwise returns false.
260
261 =cut
262
263 sub set_status_and_rated_price {
264   my($self, $status, $rated_price) = @_;
265   $self->freesidestatus($status);
266   $self->rated_price($rated_price);
267   $self->replace();
268 }
269
270 =item calldate_unix 
271
272 Parses the calldate in SQL string format and returns a UNIX timestamp.
273
274 =cut
275
276 sub calldate_unix {
277   str2time(shift->calldate);
278 }
279
280 =item startdate_sql
281
282 Parses the startdate in UNIX timestamp format and returns a string in SQL
283 format.
284
285 =cut
286
287 sub startdate_sql {
288   my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
289   $mon++;
290   $year += 1900;
291   "$year-$mon-$mday $hour:$min:$sec";
292 }
293
294 =item cdr_carrier
295
296 Returns the FS::cdr_carrier object associated with this CDR, or false if no
297 carrierid is defined.
298
299 =cut
300
301 my %carrier_cache = ();
302
303 sub cdr_carrier {
304   my $self = shift;
305   return '' unless $self->carrierid;
306   $carrier_cache{$self->carrierid} ||=
307     qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
308 }
309
310 =item carriername 
311
312 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
313 no FS::cdr_carrier object is assocated with this CDR.
314
315 =cut
316
317 sub carriername {
318   my $self = shift;
319   my $cdr_carrier = $self->cdr_carrier;
320   $cdr_carrier ? $cdr_carrier->carriername : '';
321 }
322
323 =item cdr_calltype
324
325 Returns the FS::cdr_calltype object associated with this CDR, or false if no
326 calltypenum is defined.
327
328 =cut
329
330 my %calltype_cache = ();
331
332 sub cdr_calltype {
333   my $self = shift;
334   return '' unless $self->calltypenum;
335   $calltype_cache{$self->calltypenum} ||=
336     qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
337 }
338
339 =item calltypename 
340
341 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
342 no FS::cdr_calltype object is assocated with this CDR.
343
344 =cut
345
346 sub calltypename {
347   my $self = shift;
348   my $cdr_calltype = $self->cdr_calltype;
349   $cdr_calltype ? $cdr_calltype->calltypename : '';
350 }
351
352 =item cdr_upstream_rate
353
354 Returns the upstream rate mapping (see L<FS::cdr_upstream_rate>), or the empty
355 string if no FS::cdr_upstream_rate object is associated with this CDR.
356
357 =cut
358
359 sub cdr_upstream_rate {
360   my $self = shift;
361   return '' unless $self->upstream_rateid;
362   qsearchs('cdr_upstream_rate', { 'upstream_rateid' => $self->upstream_rateid })
363     or '';
364 }
365
366 =item _convergent_format COLUMN [ COUNTRYCODE ]
367
368 Returns the number in COLUMN formatted as follows:
369
370 If the country code does not match COUNTRYCODE (default "61"), it is returned
371 unchanged.
372
373 If the country code does match COUNTRYCODE (default "61"), it is removed.  In
374 addiiton, "0" is prepended unless the number starts with 13, 18 or 19. (???)
375
376 =cut
377
378 sub _convergent_format {
379   my( $self, $field ) = ( shift, shift );
380   my $countrycode = scalar(@_) ? shift : '61'; #+61 = australia
381   #my $number = $self->$field();
382   my $number = $self->get($field);
383   #if ( $number =~ s/^(\+|011)$countrycode// ) {
384   if ( $number =~ s/^\+$countrycode// ) {
385     $number = "0$number"
386       unless $number =~ /^1[389]/; #???
387   }
388   $number;
389 }
390
391 =item downstream_csv [ OPTION => VALUE, ... ]
392
393 =cut
394
395 my %export_formats = (
396   'convergent' => [
397     'carriername', #CARRIER
398     sub { shift->_convergent_format('src') }, #SERVICE_NUMBER
399     sub { shift->_convergent_format('charged_party') }, #CHARGED_NUMBER
400     sub { time2str('%Y-%m-%d', shift->calldate_unix ) }, #DATE
401     sub { time2str('%T',       shift->calldate_unix ) }, #TIME
402     'billsec', #'duration', #DURATION
403     sub { shift->_convergent_format('dst') }, #NUMBER_DIALED
404     '', #XXX add (from prefixes in most recent email) #FROM_DESC
405     '', #XXX add (from prefixes in most recent email) #TO_DESC
406     'calltypename', #CLASS_CODE
407     'rated_price', #PRICE
408     sub { shift->rated_price ? 'Y' : 'N' }, #RATED
409     '', #OTHER_INFO
410   ],
411 );
412
413 sub downstream_csv {
414   my( $self, %opt ) = @_;
415
416   my $format = $opt{'format'}; # 'convergent';
417   return "Unknown format $format" unless exists $export_formats{$format};
418
419   eval "use Text::CSV_XS;";
420   die $@ if $@;
421   my $csv = new Text::CSV_XS;
422
423   my @columns =
424     map {
425           ref($_) ? &{$_}($self) : $self->$_();
426         }
427     @{ $export_formats{$format} };
428
429   my $status = $csv->combine(@columns);
430   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
431     unless $status;
432
433   $csv->string;
434
435 }
436
437 =back
438
439 =head1 CLASS METHODS
440
441 =over 4
442
443 =item import_formats
444
445 Returns an ordered list of key value pairs containing import format names
446 as keys (for use with batch_import) and "pretty" format names as values.
447
448 =cut
449
450 sub import_formats {
451   'asterisk' => 'Asterisk',
452   'taqua'    => 'Taqua',
453   'unitel'   => 'Unitel/RSLCOM',
454   'simple'   => 'Simple',
455 }
456
457 my($tmp_mday, $tmp_mon, $tmp_year);
458
459 sub _cdr_date_parser_maker {
460   my $field = shift;
461   return sub {
462     my( $cdr, $date ) = @_;
463     $cdr->$field( _cdr_date_parse($date) );
464   };
465 }
466
467 sub _cdr_date_parse {
468   my $date = shift;
469
470   return '' unless length($date); #that's okay, it becomes NULL
471
472   #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
473   $date =~ /^\s*(\d{4})\D(\d{1,2})\D(\d{1,2})\s+(\d{1,2})\D(\d{1,2})\D(\d{1,2})\s*$/
474     or die "unparsable date: $date"; #maybe we shouldn't die...
475   my($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
476
477   timelocal($sec, $min, $hour, $day, $mon-1, $year);
478 }
479
480 #http://www.the-asterisk-book.com/unstable/funktionen-cdr.html
481 my %amaflags = (
482   DEFAULT       => 0,
483   OMIT          => 1, #asterisk 1.4+
484   IGNORE        => 1, #asterisk 1.2
485   BILLING       => 2, #asterisk 1.4+
486   BILL          => 2, #asterisk 1.2
487   DOCUMENTATION => 3,
488   #? '' => 0,
489 );
490
491 my %import_formats = (
492   'asterisk' => [
493     'accountcode',
494     'src',
495     'dst',
496     'dcontext',
497     'clid',
498     'channel',
499     'dstchannel',
500     'lastapp',
501     'lastdata',
502     _cdr_date_parser_maker('startdate'),
503     _cdr_date_parser_maker('answerdate'),
504     _cdr_date_parser_maker('enddate'),
505     'duration',
506     'billsec',
507     'disposition',
508     sub { my($cdr, $amaflags) = @_; $cdr->amaflags($amaflags{$amaflags}); },
509     'uniqueid',
510     'userfield',
511   ],
512   'taqua' => [
513     sub { my($cdr, $field) = @_; }, #RecordType
514     sub { my($cdr, $field) = @_; },         #all10#RecordVersion
515     sub { my($cdr, $field) = @_; }, #OrigShelfNumber
516     sub { my($cdr, $field) = @_; }, #OrigCardNumber
517     sub { my($cdr, $field) = @_; }, #OrigCircuit
518     sub { my($cdr, $field) = @_; }, #OrigCircuitType
519     sub { my($cdr, $field) = @_; }, #SequenceNumber
520     sub { my($cdr, $field) = @_; }, #SessionNumber
521     sub { my($cdr, $field) = @_; }, #CallingPartyNumber
522     sub { my($cdr, $field) = @_; }, #CalledPartyNumber
523     sub { my($cdr, $field) = @_; }, #CallArrivalTime
524     sub { my($cdr, $field) = @_; }, #CallCompletionTime
525     sub { my($cdr, $field) = @_; }, #Disposition
526     sub { my($cdr, $field) = @_; }, #DispositionTime
527     sub { my($cdr, $field) = @_; }, #TCAP
528     sub { my($cdr, $field) = @_; }, #OutboundCarrierConnectTime
529     sub { my($cdr, $field) = @_; }, #OutboundCarrierDisconnectTime
530     sub { my($cdr, $field) = @_; }, #TermTrunkGroup
531     sub { my($cdr, $field) = @_; }, #TermShelfNumber
532     sub { my($cdr, $field) = @_; }, #TermCardNumber
533     sub { my($cdr, $field) = @_; }, #TermCircuit
534     sub { my($cdr, $field) = @_; }, #TermCircuitType
535     sub { my($cdr, $field) = @_; }, #OutboundCarrierId
536     sub { my($cdr, $field) = @_; }, #BillingNumber
537     sub { my($cdr, $field) = @_; }, #SubscriberNumber
538     sub { my($cdr, $field) = @_; }, #ServiceName
539     sub { my($cdr, $field) = @_; }, #ChargeTime
540     sub { my($cdr, $field) = @_; }, #ServiceInformation
541     sub { my($cdr, $field) = @_; }, #FacilityInfo
542     sub { my($cdr, $field) = @_; }, #CallTraceTime
543     sub { my($cdr, $field) = @_; },         #all-1#UniqueIndicator
544     sub { my($cdr, $field) = @_; },         #all-1#PresentationIndicator
545     sub { my($cdr, $field) = @_; },         #empty#Pin
546     sub { my($cdr, $field) = @_; }, #CallType
547     sub { my($cdr, $field) = @_; }, #OrigRateCenter
548     sub { my($cdr, $field) = @_; }, #TermRateCenter
549     sub { my($cdr, $field) = @_; }, #OrigTrunkGroup
550     'userfield',                            #empty#UserDefined
551     sub { my($cdr, $field) = @_; },         #empty#PseudoDestinationNumber
552     sub { my($cdr, $field) = @_; },         #all-1#PseudoCarrierCode
553     sub { my($cdr, $field) = @_; },         #empty#PseudoANI
554     sub { my($cdr, $field) = @_; },         #all-1#PseudoFacilityInfo
555     sub { my($cdr, $field) = @_; }, #OrigDialedDigits
556     sub { my($cdr, $field) = @_; },         #all-1#OrigOutboundCarrier
557     sub { my($cdr, $field) = @_; }, #IncomingCarrierID
558     sub { my($cdr, $field) = @_; }, #JurisdictionInfo
559     sub { my($cdr, $field) = @_; }, #OrigDestDigits
560     sub { my($cdr, $field) = @_; }, #InsertTime
561     sub { my($cdr, $field) = @_; }, #key
562     sub { my($cdr, $field) = @_; },         #empty#AMALineNumber
563     sub { my($cdr, $field) = @_; },         #empty#AMAslpID
564     sub { my($cdr, $field) = @_; },         #empty#AMADigitsDialedWC
565     sub { my($cdr, $field) = @_; }, #OpxOffHook
566     sub { my($cdr, $field) = @_; }, #OpxOnHook
567
568 #acctid - primary key
569 #calldate - Call timestamp (SQL timestamp)
570 #clid - Caller*ID with text
571 #src - Caller*ID number / Source number
572 #dst - Destination extension
573 #dcontext - Destination context
574 #channel - Channel used
575 #dstchannel - Destination channel if appropriate
576 #lastapp - Last application if appropriate
577 #lastdata - Last application data
578 #startdate - Start of call (UNIX-style integer timestamp)
579 #answerdate - Answer time of call (UNIX-style integer timestamp)
580 #enddate - End time of call (UNIX-style integer timestamp)
581 #duration - Total time in system, in seconds
582 #billsec - Total time call is up, in seconds
583 #disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY
584 #amaflags - What flags to use: BILL, IGNORE etc, specified on a per
585 #channel basis like accountcode.
586 #accountcode - CDR account number to use: account
587 #uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
588         #userfield - CDR user-defined field
589 #cdr_type - CDR type - see FS::cdr_type (Usage = 1, S&E = 7, OC&C = 8)
590 #charged_party - Service number to be billed
591 #upstream_currency - Wholesale currency from upstream
592 #upstream_price - Wholesale price from upstream
593 #upstream_rateplanid - Upstream rate plan ID
594 #rated_price - Rated (or re-rated) price
595 #distance - km (need units field?)
596 #islocal - Local - 1, Non Local = 0
597 #calltypenum - Type of call - see FS::cdr_calltype
598 #description - Description (cdr_type 7&8 only) (used for
599 #cust_bill_pkg.itemdesc)
600 #quantity - Number of items (cdr_type 7&8 only)
601 #carrierid - Upstream Carrier ID (see FS::cdr_carrier)
602 #upstream_rateid - Upstream Rate ID
603         #svcnum - Link to customer service (see FS::cust_svc)
604         #freesidestatus - NULL, done (or something)
605
606   ],
607   'unitel' => [
608     'uniqueid',
609     #'cdr_type',
610     'cdrtypenum',
611     'calldate', # may need massaging?  huh maybe not...
612     #'billsec', #XXX duration and billsec?
613                 sub { $_[0]->billsec(  $_[1] );
614                       $_[0]->duration( $_[1] );
615                     },
616     'src',
617     'dst', # XXX needs to have "+61" prepended unless /^\+/ ???
618     'charged_party',
619     'upstream_currency',
620     'upstream_price',
621     'upstream_rateplanid',
622     'distance',
623     'islocal',
624     'calltypenum',
625     'startdate',  #XXX needs massaging
626     'enddate',    #XXX same
627     'description',
628     'quantity',
629     'carrierid',
630     'upstream_rateid',
631   ],
632   'simple' => [
633
634     # Date
635     sub { my($cdr, $date) = @_;
636           $date =~ /^(\d{1,2})\/(\d{1,2})\/(\d\d(\d\d)?)$/
637             or die "unparsable date: $date"; #maybe we shouldn't die...
638           #$cdr->startdate( timelocal(0, 0, 0 ,$2, $1-1, $3) );
639           ($tmp_mday, $tmp_mon, $tmp_year) = ( $2, $1-1, $3 );
640         },
641
642     # Time
643     sub { my($cdr, $time) = @_;
644           #my($sec, $min, $hour, $mday, $mon, $year)= localtime($cdr->startdate);
645           $time =~ /^(\d{1,2}):(\d{1,2}):(\d{1,2})$/
646             or die "unparsable time: $time"; #maybe we shouldn't die...
647           #$cdr->startdate( timelocal($3, $2, $1 ,$mday, $mon, $year) );
648           $cdr->startdate(
649             timelocal($3, $2, $1 ,$tmp_mday, $tmp_mon, $tmp_year)
650           );
651         },
652
653     # Source_Number
654     'src',
655
656     # Terminating_Number
657     'dst',
658
659     # Duration
660     sub { my($cdr, $min) = @_;
661           my $sec = sprintf('%.0f', $min * 60 );
662           $cdr->billsec(  $sec );
663           $cdr->duration( $sec );
664         },
665
666   ],
667 );
668
669 my %import_header = (
670   'simple' => 1,
671   'taqua'  => 1,
672 );
673
674 =item batch_import HASHREF
675
676 Imports CDR records.  Available options are:
677
678 =over 4
679
680 =item filehandle
681
682 =item format
683
684 =back
685
686 =cut
687
688 sub batch_import {
689   my $param = shift;
690
691   my $fh = $param->{filehandle};
692   my $format = $param->{format};
693
694   return "Unknown format $format" unless exists $import_formats{$format};
695
696   eval "use Text::CSV_XS;";
697   die $@ if $@;
698
699   my $csv = new Text::CSV_XS;
700
701   my $imported = 0;
702   #my $columns;
703
704   local $SIG{HUP} = 'IGNORE';
705   local $SIG{INT} = 'IGNORE';
706   local $SIG{QUIT} = 'IGNORE';
707   local $SIG{TERM} = 'IGNORE';
708   local $SIG{TSTP} = 'IGNORE';
709   local $SIG{PIPE} = 'IGNORE';
710
711   my $oldAutoCommit = $FS::UID::AutoCommit;
712   local $FS::UID::AutoCommit = 0;
713   my $dbh = dbh;
714
715   my $body = 0;
716   my $line;
717   while ( defined($line=<$fh>) ) {
718
719     #skip header...
720     if ( ! $body++ && $import_header{'format'} && $line =~ /^[\w\, ]+$/ ) {
721       next;
722     }
723
724     $csv->parse($line) or do {
725       $dbh->rollback if $oldAutoCommit;
726       return "can't parse: ". $csv->error_input();
727     };
728
729     my @columns = $csv->fields();
730     #warn join('-',@columns);
731
732     if ( $format eq 'simple' ) {
733       @columns = map { s/^ +//; $_; } @columns;
734     }
735
736     my @later = ();
737     my %cdr =
738       map {
739
740         my $field_or_sub = $_;
741         if ( ref($field_or_sub) ) {
742           push @later, $field_or_sub, shift(@columns);
743           ();
744         } else {
745           ( $field_or_sub => shift @columns );
746         }
747
748       }
749       @{ $import_formats{$format} }
750     ;
751
752     my $cdr = new FS::cdr ( \%cdr );
753
754     while ( scalar(@later) ) {
755       my $sub = shift @later;
756       my $data = shift @later;
757       &{$sub}($cdr, $data);  # $cdr->&{$sub}($data); 
758     }
759
760     my $error = $cdr->insert;
761     if ( $error ) {
762       $dbh->rollback if $oldAutoCommit;
763       return $error;
764
765       #or just skip?
766       #next;
767     }
768
769     $imported++;
770   }
771
772   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
773
774   #might want to disable this if we skip records for any reason...
775   return "Empty file!" unless $imported;
776
777   '';
778
779 }
780
781 =back
782
783 =head1 BUGS
784
785 =head1 SEE ALSO
786
787 L<FS::Record>, schema.html from the base documentation.
788
789 =cut
790
791 1;
792