1 package FS::rate_detail;
4 use vars qw( @ISA $DEBUG $me );
5 use FS::Record qw( qsearch qsearchs dbh );
11 @ISA = qw(FS::Record);
14 $me = '[FS::rate_detail]';
18 FS::rate_detail - Object methods for rate_detail records
24 $record = new FS::rate_detail \%hash;
25 $record = new FS::rate_detail { 'column' => 'value' };
27 $error = $record->insert;
29 $error = $new_record->replace($old_record);
31 $error = $record->delete;
33 $error = $record->check;
37 An FS::rate_detail object represents an call plan rate. FS::rate_detail
38 inherits from FS::Record. The following fields are currently supported:
42 =item ratedetailnum - primary key
44 =item ratenum - rate plan (see L<FS::rate>)
46 =item orig_regionnum - call origination region
48 =item dest_regionnum - call destination region
50 =item min_included - included minutes
52 =item min_charge - charge per minute
54 =item sec_granularity - granularity in seconds, i.e. 6 or 60; 0 for per-call
56 =item classnum - usage class (see L<FS::usage_class>) if any for this rate
58 =item ratetimenum - rating time period (see L<FS::rate_time) if any
60 =item cdrtypenum - CDR type (see L<FS::cdr_type>) if any for this rate
62 =item region_group - Group in region group for rate plan
72 Creates a new call plan rate. To add the call plan rate to the database, see
75 Note that this stores the hash reference, not a distinct copy of the hash it
76 points to. You can ask the object for a copy with the I<hash> method.
80 # the new method can be inherited from FS::Record, if a table method is defined
82 sub table { 'rate_detail'; }
86 Adds this record to the database. If there is an error, returns the error,
87 otherwise returns false.
91 # the insert method can be inherited from FS::Record
95 Delete this record from the database.
99 # the delete method can be inherited from FS::Record
101 =item replace OLD_RECORD
103 Replaces the OLD_RECORD with this one in the database. If there is an error,
104 returns the error, otherwise returns false.
108 # the replace method can be inherited from FS::Record
112 Checks all fields to make sure this is a valid call plan rate. If there is
113 an error, returns the error, otherwise returns false. Called by the insert
118 # the check method should currently be supplied - FS::Record contains some
119 # data checking routines
125 $self->ut_numbern('ratedetailnum')
126 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
127 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
128 || $self->ut_foreign_key('dest_regionnum', 'rate_region', 'regionnum' )
129 || $self->ut_number('min_included')
131 #|| $self->ut_money('min_charge')
132 #good enough for now...
133 || $self->ut_float('min_charge')
135 || $self->ut_number('sec_granularity')
137 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
138 || $self->ut_enum('region_group', [ '', 'Y' ])
140 return $error if $error;
147 Returns the parent call plan (see L<FS::rate>) associated with this call plan
154 qsearchs('rate', { 'ratenum' => $self->ratenum } );
159 Returns the origination region (see L<FS::rate_region>) associated with this
166 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
171 Returns the destination region (see L<FS::rate_region>) associated with this
178 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
181 =item dest_regionname
183 Returns the name of the destination region (see L<FS::rate_region>) associated
184 with this call plan rate.
188 sub dest_regionname {
190 $self->dest_region->regionname;
193 =item dest_regionname
195 Returns a short list of the prefixes for the destination region
196 (see L<FS::rate_region>) associated with this call plan rate.
200 sub dest_prefixes_short {
202 $self->dest_region->prefixes_short;
207 Returns the L<FS::rate_time> object associated with this call
208 plan rate, if there is one.
214 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
219 Returns the I<ratetimename> field of the L<FS::rate_time> object
220 associated with this rate plan.
226 $self->ratetimenum ? $self->rate_time->ratetimename : '(default)';
231 Returns the name of the usage class (see L<FS::usage_class>) associated with
238 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
239 $usage_class ? $usage_class->classname : '';
244 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
245 rate, if there is one. If not, returns the cdrtypenum itself. This will
246 only return an empty string if cdrtypenum is NULL.
252 my $cdrtypenum = $self->cdrtypenum or return '';
253 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
254 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
265 Returns an (ordered) hash of granularity => name pairs
269 tie my %granularities, 'Tie::IxHash',
272 '30' => '30 second', # '1/2 minute',
283 Returns an (ordered) hash of conn_sec => name pairs
287 tie my %conn_secs, 'Tie::IxHash',
289 '1' => 'first second',
290 '6' => 'first 6 seconds',
291 '30' => 'first 30 seconds', # '1/2 minute',
292 '60' => 'first minute',
293 '120' => 'first 2 minutes',
294 '180' => 'first 3 minutes',
295 '300' => 'first 5 minutes',
302 =item process_edit_import
306 use Storable qw(thaw);
309 sub process_edit_import {
312 #do we actually belong in rate_detail, like 'table' says? even though we
313 # can possible create new rate records, that's a side effect, mostly we
314 # do edit rate_detail records in batch...
316 my $opt = { 'table' => 'rate_detail',
317 'params' => [], #required, apparantly
318 'formats' => { 'default' => [
327 my( $rate_detail, $g ) = @_;
328 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
329 $g = 60 if $g =~ /^\s*minute\s*$/i;
330 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
331 " for record ". Dumper($rate_detail);
332 $rate_detail->sec_granularity($1);
336 'format_headers' => { 'default' => 1, },
337 'format_types' => { 'default' => 'xls' },
341 #FS::Record::process_batch_import( $job, $opt, @_ );
343 my $table = $opt->{table};
344 my @pass_params = @{ $opt->{params} };
345 my %formats = %{ $opt->{formats} };
347 my $param = thaw(decode_base64(shift));
348 warn Dumper($param) if $DEBUG;
350 my $files = $param->{'uploaded_files'}
351 or die "No files provided.\n";
353 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
355 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
356 my $file = $dir. $files{'file'};
360 #FS::Record::batch_import( {
361 FS::rate_detail::edit_import( {
364 formats => \%formats,
365 format_types => $opt->{format_types},
366 format_headers => $opt->{format_headers},
367 format_sep_chars => $opt->{format_sep_chars},
368 format_fixedlength_formats => $opt->{format_fixedlength_formats},
373 format => $param->{format},
374 params => { map { $_ => $param->{$_} } @pass_params },
376 default_csv => $opt->{default_csv},
381 die "$error\n" if $error;
389 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
390 #could be turned into callbacks or something
395 warn "$me edit_import call with params: \n". Dumper($param)
398 my $table = $param->{table};
399 my $formats = $param->{formats};
401 my $job = $param->{job};
402 my $file = $param->{file};
403 my $format = $param->{'format'};
404 my $params = $param->{params} || {};
406 die "unknown format $format" unless exists $formats->{ $format };
408 my $type = $param->{'format_types'}
409 ? $param->{'format_types'}{ $format }
410 : $param->{type} || 'csv';
413 if ( $file =~ /\.(\w+)$/i ) {
417 warn "can't parse file type from filename $file; defaulting to CSV";
421 if $param->{'default_csv'} && $type ne 'xls';
424 my $header = $param->{'format_headers'}
425 ? $param->{'format_headers'}{ $param->{'format'} }
428 my $sep_char = $param->{'format_sep_chars'}
429 ? $param->{'format_sep_chars'}{ $param->{'format'} }
432 my $fixedlength_format =
433 $param->{'format_fixedlength_formats'}
434 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
437 my @fields = @{ $formats->{ $format } };
443 my @header = (); #edit_import
444 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
446 if ( $type eq 'csv' ) {
449 $attr{sep_char} = $sep_char if $sep_char;
450 $parser = new Text::CSV_XS \%attr;
452 } elsif ( $type eq 'fixedlength' ) {
454 eval "use Parse::FixedLength;";
456 $parser = new Parse::FixedLength $fixedlength_format;
459 die "Unknown file type $type\n";
462 @buffer = split(/\r?\n/, slurp($file) );
463 splice(@buffer, 0, ($header || 0) );
464 $count = scalar(@buffer);
466 } elsif ( $type eq 'xls' ) {
468 eval "use Spreadsheet::ParseExcel;";
471 eval "use DateTime::Format::Excel;";
472 #for now, just let the error be thrown if it is used, since only CDR
473 # formats bill_west and troop use it, not other excel-parsing things
476 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
478 $parser = $excel->{Worksheet}[0]; #first sheet
480 $count = $parser->{MaxRow} || $parser->{MinRow};
485 #edit_import - need some magic to parse the header
487 my @header_row = @{ $parser->{Cells}[$0] };
488 @header = map $_->{Val}, @header_row;
492 die "Unknown file type $type\n";
497 local $SIG{HUP} = 'IGNORE';
498 local $SIG{INT} = 'IGNORE';
499 local $SIG{QUIT} = 'IGNORE';
500 local $SIG{TERM} = 'IGNORE';
501 local $SIG{TSTP} = 'IGNORE';
502 local $SIG{PIPE} = 'IGNORE';
504 my $oldAutoCommit = $FS::UID::AutoCommit;
505 local $FS::UID::AutoCommit = 0;
508 #edit_import - use the header to setup looping over different rates
511 splice(@header,0,4); # # Region Country Prefixes
512 while ( my @next = splice(@header,0,4) ) {
514 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
515 $rate = qsearchs('rate', { 'ratenum' => $1 } )
516 or die "unknown ratenum $1";
517 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
518 $rate = new FS::rate { 'ratename' => $2 };
519 my $error = $rate->insert;
521 $dbh->rollback if $oldAutoCommit;
522 return "error inserting new rate: $error\n";
532 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
536 if ( $type eq 'csv' ) {
538 last unless scalar(@buffer);
539 $line = shift(@buffer);
541 $parser->parse($line) or do {
542 $dbh->rollback if $oldAutoCommit;
543 return "can't parse: ". $parser->error_input();
545 @columns = $parser->fields();
547 } elsif ( $type eq 'fixedlength' ) {
549 @columns = $parser->parse($line);
551 } elsif ( $type eq 'xls' ) {
553 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
554 || ! $parser->{Cells}[$row];
556 my @row = @{ $parser->{Cells}[$row] };
557 @columns = map $_->{Val}, @row;
560 #warn $z++. ": $_\n" for @columns;
563 die "Unknown file type $type\n";
568 my @repeat = @columns[0..3];
570 foreach my $rate ( @rate ) {
575 foreach my $field ( @fields ) {
577 my $value = shift @columns;
579 if ( ref($field) eq 'CODE' ) {
580 #&{$field}(\%hash, $value);
581 push @later, $field, $value;
583 } elsif ($field) { #edit_import
584 #??? $hash{$field} = $value if length($value);
585 $hash{$field} = $value if defined($value) && length($value);
590 unshift @columns, @repeat; #edit_import put these back on for next time
592 my $class = "FS::$table";
594 my $record = $class->new( \%hash );
596 $record->ratenum($rate->ratenum); #edit_import
598 #edit_improt n/a my $param = {};
599 while ( scalar(@later) ) {
600 my $sub = shift @later;
601 my $data = shift @later;
602 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
603 &{$sub}($record, $data); #edit_import - don't have $conf
604 #edit_import wrong loop last if exists( $param->{skiprow} );
606 #edit_import wrong loop next if exists( $param->{skiprow} );
608 #edit_import update or insert, not just insert
611 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
616 $record->ratedetailnum($old->ratedetailnum);
617 $error = $record->replace($old)
623 $dbh->rollback if $oldAutoCommit;
624 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
632 if ( $job && time - $min_sec > $last ) { #progress bar
633 $job->update_statustext( int(100 * $imported / $count) );
639 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
641 return "Empty file!" unless $imported || $param->{empty_ok};
653 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
654 schema.html from the base documentation.