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_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
137 || $self->ut_number('min_included')
139 #|| $self->ut_money('min_charge')
140 #good enough for now...
141 || $self->ut_floatn('conn_charge')
142 || $self->ut_floatn('conn_cost')
143 || $self->ut_float('min_charge')
144 || $self->ut_floatn('min_cost')
146 || $self->ut_number('sec_granularity')
148 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
149 || $self->ut_enum('region_group', [ '', 'Y' ])
151 || $self->ut_floatn('upstream_mult_charge')
152 || $self->ut_floatn('upstream_mult_cost')
154 return $error if $error;
161 Returns the parent call plan (see L<FS::rate>) associated with this call plan
168 qsearchs('rate', { 'ratenum' => $self->ratenum } );
173 Returns the origination region (see L<FS::rate_region>) associated with this
180 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
185 Returns the destination region (see L<FS::rate_region>) associated with this
192 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
195 =item dest_regionname
197 Returns the name of the destination region (see L<FS::rate_region>) associated
198 with this call plan rate.
202 sub dest_regionname {
204 my $dest_region = $self->dest_region;
205 $dest_region ? $dest_region->regionname : 'Global default';
206 # should be 'Anywhere' or something, to indicate that it's the
207 # cross-region default
210 =item dest_prefixes_short
212 Returns a short list of the prefixes for the destination region
213 (see L<FS::rate_region>) associated with this call plan rate.
217 sub dest_prefixes_short {
219 my $dest_region = $self->dest_region;
220 $dest_region ? $dest_region->prefixes_short : '';
225 Returns the L<FS::rate_time> object associated with this call
226 plan rate, if there is one.
232 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
237 Returns the I<ratetimename> field of the L<FS::rate_time> object
238 associated with this rate plan.
244 $self->ratetimenum ? $self->rate_time->ratetimename : '(any time)';
249 Returns the name of the usage class (see L<FS::usage_class>) associated with
256 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
257 $usage_class ? $usage_class->classname : '';
262 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
263 rate, if there is one. If not, returns the cdrtypenum itself. This will
264 only return an empty string if cdrtypenum is NULL.
270 my $cdrtypenum = $self->cdrtypenum or return '';
271 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
272 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
283 Returns an (ordered) hash of granularity => name pairs
287 tie my %granularities, 'Tie::IxHash',
290 '30' => '30 second', # '1/2 minute',
301 Returns an (ordered) hash of conn_sec => name pairs
305 tie my %conn_secs, 'Tie::IxHash',
307 '1' => 'first second',
308 '6' => 'first 6 seconds',
309 '30' => 'first 30 seconds', # '1/2 minute',
310 '60' => 'first minute',
311 '120' => 'first 2 minutes',
312 '180' => 'first 3 minutes',
313 '300' => 'first 5 minutes',
320 =item process_edit_import
324 use Storable qw(thaw);
327 sub process_edit_import {
330 #do we actually belong in rate_detail, like 'table' says? even though we
331 # can possible create new rate records, that's a side effect, mostly we
332 # do edit rate_detail records in batch...
334 my $opt = { 'table' => 'rate_detail',
335 'params' => [], #required, apparantly
336 'formats' => { 'default' => [
345 my( $rate_detail, $g ) = @_;
346 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
347 $g = 60 if $g =~ /^\s*minute\s*$/i;
348 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
349 " for record ". Dumper($rate_detail);
350 $rate_detail->sec_granularity($1);
354 'format_headers' => { 'default' => 1, },
355 'format_types' => { 'default' => 'xls' },
359 #FS::Record::process_batch_import( $job, $opt, @_ );
361 my $table = $opt->{table};
362 my @pass_params = @{ $opt->{params} };
363 my %formats = %{ $opt->{formats} };
365 my $param = thaw(decode_base64(shift));
366 warn Dumper($param) if $DEBUG;
368 my $files = $param->{'uploaded_files'}
369 or die "No files provided.\n";
371 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
373 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
374 my $file = $dir. $files{'file'};
378 #FS::Record::batch_import( {
379 FS::rate_detail::edit_import( {
382 formats => \%formats,
383 format_types => $opt->{format_types},
384 format_headers => $opt->{format_headers},
385 format_sep_chars => $opt->{format_sep_chars},
386 format_fixedlength_formats => $opt->{format_fixedlength_formats},
391 format => $param->{format},
392 params => { map { $_ => $param->{$_} } @pass_params },
394 default_csv => $opt->{default_csv},
399 die "$error\n" if $error;
407 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
408 #could be turned into callbacks or something
413 warn "$me edit_import call with params: \n". Dumper($param)
416 my $table = $param->{table};
417 my $formats = $param->{formats};
419 my $job = $param->{job};
420 my $file = $param->{file};
421 my $format = $param->{'format'};
422 my $params = $param->{params} || {};
424 die "unknown format $format" unless exists $formats->{ $format };
426 my $type = $param->{'format_types'}
427 ? $param->{'format_types'}{ $format }
428 : $param->{type} || 'csv';
431 if ( $file =~ /\.(\w+)$/i ) {
435 warn "can't parse file type from filename $file; defaulting to CSV";
439 if $param->{'default_csv'} && $type ne 'xls';
442 my $header = $param->{'format_headers'}
443 ? $param->{'format_headers'}{ $param->{'format'} }
446 my $sep_char = $param->{'format_sep_chars'}
447 ? $param->{'format_sep_chars'}{ $param->{'format'} }
450 my $fixedlength_format =
451 $param->{'format_fixedlength_formats'}
452 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
455 my @fields = @{ $formats->{ $format } };
461 my @header = (); #edit_import
462 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
464 if ( $type eq 'csv' ) {
467 $attr{sep_char} = $sep_char if $sep_char;
468 $parser = new Text::CSV_XS \%attr;
470 } elsif ( $type eq 'fixedlength' ) {
472 eval "use Parse::FixedLength;";
474 $parser = new Parse::FixedLength $fixedlength_format;
477 die "Unknown file type $type\n";
480 @buffer = split(/\r?\n/, slurp($file) );
481 splice(@buffer, 0, ($header || 0) );
482 $count = scalar(@buffer);
484 } elsif ( $type eq 'xls' ) {
486 eval "use Spreadsheet::ParseExcel;";
489 eval "use DateTime::Format::Excel;";
490 #for now, just let the error be thrown if it is used, since only CDR
491 # formats bill_west and troop use it, not other excel-parsing things
494 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
496 $parser = $excel->{Worksheet}[0]; #first sheet
498 $count = $parser->{MaxRow} || $parser->{MinRow};
503 #edit_import - need some magic to parse the header
505 my @header_row = @{ $parser->{Cells}[$0] };
506 @header = map $_->{Val}, @header_row;
510 die "Unknown file type $type\n";
515 local $SIG{HUP} = 'IGNORE';
516 local $SIG{INT} = 'IGNORE';
517 local $SIG{QUIT} = 'IGNORE';
518 local $SIG{TERM} = 'IGNORE';
519 local $SIG{TSTP} = 'IGNORE';
520 local $SIG{PIPE} = 'IGNORE';
522 my $oldAutoCommit = $FS::UID::AutoCommit;
523 local $FS::UID::AutoCommit = 0;
526 #edit_import - use the header to setup looping over different rates
529 splice(@header,0,4); # # Region Country Prefixes
530 while ( my @next = splice(@header,0,4) ) {
532 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
533 $rate = qsearchs('rate', { 'ratenum' => $1 } )
534 or die "unknown ratenum $1";
535 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
536 $rate = new FS::rate { 'ratename' => $2 };
537 my $error = $rate->insert;
539 $dbh->rollback if $oldAutoCommit;
540 return "error inserting new rate: $error\n";
550 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
554 if ( $type eq 'csv' ) {
556 last unless scalar(@buffer);
557 $line = shift(@buffer);
559 $parser->parse($line) or do {
560 $dbh->rollback if $oldAutoCommit;
561 return "can't parse: ". $parser->error_input();
563 @columns = $parser->fields();
565 } elsif ( $type eq 'fixedlength' ) {
567 @columns = $parser->parse($line);
569 } elsif ( $type eq 'xls' ) {
571 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
572 || ! $parser->{Cells}[$row];
574 my @row = @{ $parser->{Cells}[$row] };
575 @columns = map $_->{Val}, @row;
578 #warn $z++. ": $_\n" for @columns;
581 die "Unknown file type $type\n";
586 my @repeat = @columns[0..3];
588 foreach my $rate ( @rate ) {
593 foreach my $field ( @fields ) {
595 my $value = shift @columns;
597 if ( ref($field) eq 'CODE' ) {
598 #&{$field}(\%hash, $value);
599 push @later, $field, $value;
601 } elsif ($field) { #edit_import
602 #??? $hash{$field} = $value if length($value);
603 $hash{$field} = $value if defined($value) && length($value);
608 unshift @columns, @repeat; #edit_import put these back on for next time
610 my $class = "FS::$table";
612 my $record = $class->new( \%hash );
614 $record->ratenum($rate->ratenum); #edit_import
616 #edit_improt n/a my $param = {};
617 while ( scalar(@later) ) {
618 my $sub = shift @later;
619 my $data = shift @later;
620 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
621 &{$sub}($record, $data); #edit_import - don't have $conf
622 #edit_import wrong loop last if exists( $param->{skiprow} );
624 #edit_import wrong loop next if exists( $param->{skiprow} );
626 #edit_import update or insert, not just insert
629 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
634 $record->ratedetailnum($old->ratedetailnum);
635 $error = $record->replace($old)
641 $dbh->rollback if $oldAutoCommit;
642 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
650 if ( $job && time - $min_sec > $last ) { #progress bar
651 $job->update_statustext( int(100 * $imported / $count) );
657 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
659 return "Empty file!" unless $imported || $param->{empty_ok};
671 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
672 schema.html from the base documentation.