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
64 =item upstream_mult_charge - the multiplier to apply to the upstream price.
65 Defaults to zero, and should stay zero unless this rate is intended to include
66 a markup on pre-rated CDRs.
68 =item upstream_mult_cost - the multiplier to apply to the upstream price to
69 calculate the wholesale cost.
79 Creates a new call plan rate. To add the call plan rate to the database, see
82 Note that this stores the hash reference, not a distinct copy of the hash it
83 points to. You can ask the object for a copy with the I<hash> method.
87 # the new method can be inherited from FS::Record, if a table method is defined
89 sub table { 'rate_detail'; }
93 Adds this record to the database. If there is an error, returns the error,
94 otherwise returns false.
98 # the insert method can be inherited from FS::Record
102 Delete this record from the database.
106 # the delete method can be inherited from FS::Record
108 =item replace OLD_RECORD
110 Replaces the OLD_RECORD with this one in the database. If there is an error,
111 returns the error, otherwise returns false.
115 # the replace method can be inherited from FS::Record
119 Checks all fields to make sure this is a valid call plan rate. If there is
120 an error, returns the error, otherwise returns false. Called by the insert
125 # the check method should currently be supplied - FS::Record contains some
126 # data checking routines
132 $self->ut_numbern('ratedetailnum')
133 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
134 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
135 || $self->ut_foreign_keyn('dest_regionnum', 'rate_region', 'regionnum' )
136 || $self->ut_number('min_included')
138 #|| $self->ut_money('min_charge')
139 #good enough for now...
140 || $self->ut_floatn('conn_charge')
141 || $self->ut_floatn('conn_cost')
142 || $self->ut_float('min_charge')
143 || $self->ut_floatn('min_cost')
145 || $self->ut_number('sec_granularity')
147 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
148 || $self->ut_enum('region_group', [ '', 'Y' ])
150 || $self->ut_floatn('upstream_mult_charge')
151 || $self->ut_floatn('upstream_mult_cost')
153 return $error if $error;
160 Returns the parent call plan (see L<FS::rate>) associated with this call plan
167 qsearchs('rate', { 'ratenum' => $self->ratenum } );
172 Returns the origination region (see L<FS::rate_region>) associated with this
179 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
184 Returns the destination region (see L<FS::rate_region>) associated with this
191 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
194 =item dest_regionname
196 Returns the name of the destination region (see L<FS::rate_region>) associated
197 with this call plan rate.
201 sub dest_regionname {
203 my $dest_region = $self->dest_region;
204 $dest_region ? $dest_region->regionname : 'Global default';
207 =item dest_prefixes_short
209 Returns a short list of the prefixes for the destination region
210 (see L<FS::rate_region>) associated with this call plan rate.
214 sub dest_prefixes_short {
216 my $dest_region = $self->dest_region;
217 $dest_region ? $dest_region->prefixes_short : '';
222 Returns the L<FS::rate_time> object associated with this call
223 plan rate, if there is one.
229 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
234 Returns the I<ratetimename> field of the L<FS::rate_time> object
235 associated with this rate plan.
241 $self->ratetimenum ? $self->rate_time->ratetimename : '(default)';
246 Returns the name of the usage class (see L<FS::usage_class>) associated with
253 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
254 $usage_class ? $usage_class->classname : '';
259 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
260 rate, if there is one. If not, returns the cdrtypenum itself. This will
261 only return an empty string if cdrtypenum is NULL.
267 my $cdrtypenum = $self->cdrtypenum or return '';
268 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
269 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
280 Returns an (ordered) hash of granularity => name pairs
284 tie my %granularities, 'Tie::IxHash',
287 '30' => '30 second', # '1/2 minute',
298 Returns an (ordered) hash of conn_sec => name pairs
302 tie my %conn_secs, 'Tie::IxHash',
304 '1' => 'first second',
305 '6' => 'first 6 seconds',
306 '30' => 'first 30 seconds', # '1/2 minute',
307 '60' => 'first minute',
308 '120' => 'first 2 minutes',
309 '180' => 'first 3 minutes',
310 '300' => 'first 5 minutes',
317 =item process_edit_import
321 use Storable qw(thaw);
324 sub process_edit_import {
327 #do we actually belong in rate_detail, like 'table' says? even though we
328 # can possible create new rate records, that's a side effect, mostly we
329 # do edit rate_detail records in batch...
331 my $opt = { 'table' => 'rate_detail',
332 'params' => [], #required, apparantly
333 'formats' => { 'default' => [
342 my( $rate_detail, $g ) = @_;
343 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
344 $g = 60 if $g =~ /^\s*minute\s*$/i;
345 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
346 " for record ". Dumper($rate_detail);
347 $rate_detail->sec_granularity($1);
351 'format_headers' => { 'default' => 1, },
352 'format_types' => { 'default' => 'xls' },
356 #FS::Record::process_batch_import( $job, $opt, @_ );
358 my $table = $opt->{table};
359 my @pass_params = @{ $opt->{params} };
360 my %formats = %{ $opt->{formats} };
362 my $param = thaw(decode_base64(shift));
363 warn Dumper($param) if $DEBUG;
365 my $files = $param->{'uploaded_files'}
366 or die "No files provided.\n";
368 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
370 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
371 my $file = $dir. $files{'file'};
375 #FS::Record::batch_import( {
376 FS::rate_detail::edit_import( {
379 formats => \%formats,
380 format_types => $opt->{format_types},
381 format_headers => $opt->{format_headers},
382 format_sep_chars => $opt->{format_sep_chars},
383 format_fixedlength_formats => $opt->{format_fixedlength_formats},
388 format => $param->{format},
389 params => { map { $_ => $param->{$_} } @pass_params },
391 default_csv => $opt->{default_csv},
396 die "$error\n" if $error;
404 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
405 #could be turned into callbacks or something
410 warn "$me edit_import call with params: \n". Dumper($param)
413 my $table = $param->{table};
414 my $formats = $param->{formats};
416 my $job = $param->{job};
417 my $file = $param->{file};
418 my $format = $param->{'format'};
419 my $params = $param->{params} || {};
421 die "unknown format $format" unless exists $formats->{ $format };
423 my $type = $param->{'format_types'}
424 ? $param->{'format_types'}{ $format }
425 : $param->{type} || 'csv';
428 if ( $file =~ /\.(\w+)$/i ) {
432 warn "can't parse file type from filename $file; defaulting to CSV";
436 if $param->{'default_csv'} && $type ne 'xls';
439 my $header = $param->{'format_headers'}
440 ? $param->{'format_headers'}{ $param->{'format'} }
443 my $sep_char = $param->{'format_sep_chars'}
444 ? $param->{'format_sep_chars'}{ $param->{'format'} }
447 my $fixedlength_format =
448 $param->{'format_fixedlength_formats'}
449 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
452 my @fields = @{ $formats->{ $format } };
458 my @header = (); #edit_import
459 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
461 if ( $type eq 'csv' ) {
464 $attr{sep_char} = $sep_char if $sep_char;
465 $parser = new Text::CSV_XS \%attr;
467 } elsif ( $type eq 'fixedlength' ) {
469 eval "use Parse::FixedLength;";
471 $parser = new Parse::FixedLength $fixedlength_format;
474 die "Unknown file type $type\n";
477 @buffer = split(/\r?\n/, slurp($file) );
478 splice(@buffer, 0, ($header || 0) );
479 $count = scalar(@buffer);
481 } elsif ( $type eq 'xls' ) {
483 eval "use Spreadsheet::ParseExcel;";
486 eval "use DateTime::Format::Excel;";
487 #for now, just let the error be thrown if it is used, since only CDR
488 # formats bill_west and troop use it, not other excel-parsing things
491 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
493 $parser = $excel->{Worksheet}[0]; #first sheet
495 $count = $parser->{MaxRow} || $parser->{MinRow};
500 #edit_import - need some magic to parse the header
502 my @header_row = @{ $parser->{Cells}[$0] };
503 @header = map $_->{Val}, @header_row;
507 die "Unknown file type $type\n";
512 local $SIG{HUP} = 'IGNORE';
513 local $SIG{INT} = 'IGNORE';
514 local $SIG{QUIT} = 'IGNORE';
515 local $SIG{TERM} = 'IGNORE';
516 local $SIG{TSTP} = 'IGNORE';
517 local $SIG{PIPE} = 'IGNORE';
519 my $oldAutoCommit = $FS::UID::AutoCommit;
520 local $FS::UID::AutoCommit = 0;
523 #edit_import - use the header to setup looping over different rates
526 splice(@header,0,4); # # Region Country Prefixes
527 while ( my @next = splice(@header,0,4) ) {
529 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
530 $rate = qsearchs('rate', { 'ratenum' => $1 } )
531 or die "unknown ratenum $1";
532 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
533 $rate = new FS::rate { 'ratename' => $2 };
534 my $error = $rate->insert;
536 $dbh->rollback if $oldAutoCommit;
537 return "error inserting new rate: $error\n";
547 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
551 if ( $type eq 'csv' ) {
553 last unless scalar(@buffer);
554 $line = shift(@buffer);
556 $parser->parse($line) or do {
557 $dbh->rollback if $oldAutoCommit;
558 return "can't parse: ". $parser->error_input();
560 @columns = $parser->fields();
562 } elsif ( $type eq 'fixedlength' ) {
564 @columns = $parser->parse($line);
566 } elsif ( $type eq 'xls' ) {
568 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
569 || ! $parser->{Cells}[$row];
571 my @row = @{ $parser->{Cells}[$row] };
572 @columns = map $_->{Val}, @row;
575 #warn $z++. ": $_\n" for @columns;
578 die "Unknown file type $type\n";
583 my @repeat = @columns[0..3];
585 foreach my $rate ( @rate ) {
590 foreach my $field ( @fields ) {
592 my $value = shift @columns;
594 if ( ref($field) eq 'CODE' ) {
595 #&{$field}(\%hash, $value);
596 push @later, $field, $value;
598 } elsif ($field) { #edit_import
599 #??? $hash{$field} = $value if length($value);
600 $hash{$field} = $value if defined($value) && length($value);
605 unshift @columns, @repeat; #edit_import put these back on for next time
607 my $class = "FS::$table";
609 my $record = $class->new( \%hash );
611 $record->ratenum($rate->ratenum); #edit_import
613 #edit_improt n/a my $param = {};
614 while ( scalar(@later) ) {
615 my $sub = shift @later;
616 my $data = shift @later;
617 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
618 &{$sub}($record, $data); #edit_import - don't have $conf
619 #edit_import wrong loop last if exists( $param->{skiprow} );
621 #edit_import wrong loop next if exists( $param->{skiprow} );
623 #edit_import update or insert, not just insert
626 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
631 $record->ratedetailnum($old->ratedetailnum);
632 $error = $record->replace($old)
638 $dbh->rollback if $oldAutoCommit;
639 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
647 if ( $job && time - $min_sec > $last ) { #progress bar
648 $job->update_statustext( int(100 * $imported / $count) );
654 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
656 return "Empty file!" unless $imported || $param->{empty_ok};
668 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
669 schema.html from the base documentation.