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
70 Creates a new call plan rate. To add the call plan rate to the database, see
73 Note that this stores the hash reference, not a distinct copy of the hash it
74 points to. You can ask the object for a copy with the I<hash> method.
78 # the new method can be inherited from FS::Record, if a table method is defined
80 sub table { 'rate_detail'; }
84 Adds this record to the database. If there is an error, returns the error,
85 otherwise returns false.
89 # the insert method can be inherited from FS::Record
93 Delete this record from the database.
97 # the delete method can be inherited from FS::Record
99 =item replace OLD_RECORD
101 Replaces the OLD_RECORD with this one in the database. If there is an error,
102 returns the error, otherwise returns false.
106 # the replace method can be inherited from FS::Record
110 Checks all fields to make sure this is a valid call plan rate. If there is
111 an error, returns the error, otherwise returns false. Called by the insert
116 # the check method should currently be supplied - FS::Record contains some
117 # data checking routines
123 $self->ut_numbern('ratedetailnum')
124 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
125 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
126 || $self->ut_foreign_key('dest_regionnum', 'rate_region', 'regionnum' )
127 || $self->ut_number('min_included')
129 #|| $self->ut_money('min_charge')
130 #good enough for now...
131 || $self->ut_float('min_charge')
133 || $self->ut_number('sec_granularity')
135 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
137 return $error if $error;
144 Returns the parent call plan (see L<FS::rate>) associated with this call plan
151 qsearchs('rate', { 'ratenum' => $self->ratenum } );
156 Returns the origination region (see L<FS::rate_region>) associated with this
163 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
168 Returns the destination region (see L<FS::rate_region>) associated with this
175 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
178 =item dest_regionname
180 Returns the name of the destination region (see L<FS::rate_region>) associated
181 with this call plan rate.
185 sub dest_regionname {
187 $self->dest_region->regionname;
190 =item dest_regionname
192 Returns a short list of the prefixes for the destination region
193 (see L<FS::rate_region>) associated with this call plan rate.
197 sub dest_prefixes_short {
199 $self->dest_region->prefixes_short;
204 Returns the L<FS::rate_time> object associated with this call
205 plan rate, if there is one.
211 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
216 Returns the I<ratetimename> field of the L<FS::rate_time> object
217 associated with this rate plan.
223 $self->ratetimenum ? $self->rate_time->ratetimename : '(default)';
228 Returns the name of the usage class (see L<FS::usage_class>) associated with
235 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
236 $usage_class ? $usage_class->classname : '';
241 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
242 rate, if there is one. If not, returns the cdrtypenum itself. This will
243 only return an empty string if cdrtypenum is NULL.
249 my $cdrtypenum = $self->cdrtypenum or return '';
250 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
251 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
262 Returns an (ordered) hash of granularity => name pairs
266 tie my %granularities, 'Tie::IxHash',
269 '30' => '30 second', # '1/2 minute',
280 Returns an (ordered) hash of conn_sec => name pairs
284 tie my %conn_secs, 'Tie::IxHash',
286 '1' => 'first second',
287 '6' => 'first 6 seconds',
288 '30' => 'first 30 seconds', # '1/2 minute',
289 '60' => 'first minute',
290 '120' => 'first 2 minutes',
291 '180' => 'first 3 minutes',
292 '300' => 'first 5 minutes',
299 =item process_edit_import
303 use Storable qw(thaw);
306 sub process_edit_import {
309 #do we actually belong in rate_detail, like 'table' says? even though we
310 # can possible create new rate records, that's a side effect, mostly we
311 # do edit rate_detail records in batch...
313 my $opt = { 'table' => 'rate_detail',
314 'params' => [], #required, apparantly
315 'formats' => { 'default' => [
324 my( $rate_detail, $g ) = @_;
325 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
326 $g = 60 if $g =~ /^\s*minute\s*$/i;
327 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
328 " for record ". Dumper($rate_detail);
329 $rate_detail->sec_granularity($1);
333 'format_headers' => { 'default' => 1, },
334 'format_types' => { 'default' => 'xls' },
338 #FS::Record::process_batch_import( $job, $opt, @_ );
340 my $table = $opt->{table};
341 my @pass_params = @{ $opt->{params} };
342 my %formats = %{ $opt->{formats} };
344 my $param = thaw(decode_base64(shift));
345 warn Dumper($param) if $DEBUG;
347 my $files = $param->{'uploaded_files'}
348 or die "No files provided.\n";
350 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
352 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
353 my $file = $dir. $files{'file'};
357 #FS::Record::batch_import( {
358 FS::rate_detail::edit_import( {
361 formats => \%formats,
362 format_types => $opt->{format_types},
363 format_headers => $opt->{format_headers},
364 format_sep_chars => $opt->{format_sep_chars},
365 format_fixedlength_formats => $opt->{format_fixedlength_formats},
370 format => $param->{format},
371 params => { map { $_ => $param->{$_} } @pass_params },
373 default_csv => $opt->{default_csv},
378 die "$error\n" if $error;
386 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
387 #could be turned into callbacks or something
392 warn "$me edit_import call with params: \n". Dumper($param)
395 my $table = $param->{table};
396 my $formats = $param->{formats};
398 my $job = $param->{job};
399 my $file = $param->{file};
400 my $format = $param->{'format'};
401 my $params = $param->{params} || {};
403 die "unknown format $format" unless exists $formats->{ $format };
405 my $type = $param->{'format_types'}
406 ? $param->{'format_types'}{ $format }
407 : $param->{type} || 'csv';
410 if ( $file =~ /\.(\w+)$/i ) {
414 warn "can't parse file type from filename $file; defaulting to CSV";
418 if $param->{'default_csv'} && $type ne 'xls';
421 my $header = $param->{'format_headers'}
422 ? $param->{'format_headers'}{ $param->{'format'} }
425 my $sep_char = $param->{'format_sep_chars'}
426 ? $param->{'format_sep_chars'}{ $param->{'format'} }
429 my $fixedlength_format =
430 $param->{'format_fixedlength_formats'}
431 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
434 my @fields = @{ $formats->{ $format } };
440 my @header = (); #edit_import
441 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
443 if ( $type eq 'csv' ) {
446 $attr{sep_char} = $sep_char if $sep_char;
447 $parser = new Text::CSV_XS \%attr;
449 } elsif ( $type eq 'fixedlength' ) {
451 eval "use Parse::FixedLength;";
453 $parser = new Parse::FixedLength $fixedlength_format;
456 die "Unknown file type $type\n";
459 @buffer = split(/\r?\n/, slurp($file) );
460 splice(@buffer, 0, ($header || 0) );
461 $count = scalar(@buffer);
463 } elsif ( $type eq 'xls' ) {
465 eval "use Spreadsheet::ParseExcel;";
468 eval "use DateTime::Format::Excel;";
469 #for now, just let the error be thrown if it is used, since only CDR
470 # formats bill_west and troop use it, not other excel-parsing things
473 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
475 $parser = $excel->{Worksheet}[0]; #first sheet
477 $count = $parser->{MaxRow} || $parser->{MinRow};
482 #edit_import - need some magic to parse the header
484 my @header_row = @{ $parser->{Cells}[$0] };
485 @header = map $_->{Val}, @header_row;
489 die "Unknown file type $type\n";
494 local $SIG{HUP} = 'IGNORE';
495 local $SIG{INT} = 'IGNORE';
496 local $SIG{QUIT} = 'IGNORE';
497 local $SIG{TERM} = 'IGNORE';
498 local $SIG{TSTP} = 'IGNORE';
499 local $SIG{PIPE} = 'IGNORE';
501 my $oldAutoCommit = $FS::UID::AutoCommit;
502 local $FS::UID::AutoCommit = 0;
505 #edit_import - use the header to setup looping over different rates
508 splice(@header,0,4); # # Region Country Prefixes
509 while ( my @next = splice(@header,0,4) ) {
511 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
512 $rate = qsearchs('rate', { 'ratenum' => $1 } )
513 or die "unknown ratenum $1";
514 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
515 $rate = new FS::rate { 'ratename' => $2 };
516 my $error = $rate->insert;
518 $dbh->rollback if $oldAutoCommit;
519 return "error inserting new rate: $error\n";
529 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
533 if ( $type eq 'csv' ) {
535 last unless scalar(@buffer);
536 $line = shift(@buffer);
538 $parser->parse($line) or do {
539 $dbh->rollback if $oldAutoCommit;
540 return "can't parse: ". $parser->error_input();
542 @columns = $parser->fields();
544 } elsif ( $type eq 'fixedlength' ) {
546 @columns = $parser->parse($line);
548 } elsif ( $type eq 'xls' ) {
550 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
551 || ! $parser->{Cells}[$row];
553 my @row = @{ $parser->{Cells}[$row] };
554 @columns = map $_->{Val}, @row;
557 #warn $z++. ": $_\n" for @columns;
560 die "Unknown file type $type\n";
565 my @repeat = @columns[0..3];
567 foreach my $rate ( @rate ) {
572 foreach my $field ( @fields ) {
574 my $value = shift @columns;
576 if ( ref($field) eq 'CODE' ) {
577 #&{$field}(\%hash, $value);
578 push @later, $field, $value;
580 } elsif ($field) { #edit_import
581 #??? $hash{$field} = $value if length($value);
582 $hash{$field} = $value if defined($value) && length($value);
587 unshift @columns, @repeat; #edit_import put these back on for next time
589 my $class = "FS::$table";
591 my $record = $class->new( \%hash );
593 $record->ratenum($rate->ratenum); #edit_import
595 #edit_improt n/a my $param = {};
596 while ( scalar(@later) ) {
597 my $sub = shift @later;
598 my $data = shift @later;
599 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
600 &{$sub}($record, $data); #edit_import - don't have $conf
601 #edit_import wrong loop last if exists( $param->{skiprow} );
603 #edit_import wrong loop next if exists( $param->{skiprow} );
605 #edit_import update or insert, not just insert
608 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
613 $record->ratedetailnum($old->ratedetailnum);
614 $error = $record->replace($old)
620 $dbh->rollback if $oldAutoCommit;
621 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
629 if ( $job && time - $min_sec > $last ) { #progress bar
630 $job->update_statustext( int(100 * $imported / $count) );
636 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
638 return "Empty file!" unless $imported || $param->{empty_ok};
650 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
651 schema.html from the base documentation.