1 package FS::rate_detail;
2 use base qw(FS::Record);
5 use vars qw( $DEBUG $me );
7 use FS::Record qw( qsearch qsearchs dbh );
13 $me = '[FS::rate_detail]';
17 FS::rate_detail - Object methods for rate_detail records
23 $record = new FS::rate_detail \%hash;
24 $record = new FS::rate_detail { 'column' => 'value' };
26 $error = $record->insert;
28 $error = $new_record->replace($old_record);
30 $error = $record->delete;
32 $error = $record->check;
36 An FS::rate_detail object represents an call plan rate. FS::rate_detail
37 inherits from FS::Record. The following fields are currently supported:
41 =item ratedetailnum - primary key
43 =item ratenum - rate plan (see L<FS::rate>)
45 =item orig_regionnum - call origination region
47 =item dest_regionnum - call destination region
49 =item min_included - included minutes
51 =item min_charge - charge per minute
53 =item sec_granularity - granularity in seconds, i.e. 6 or 60; 0 for per-call
55 =item classnum - usage class (see L<FS::usage_class>) if any for this rate
57 =item ratetimenum - rating time period (see L<FS::rate_time) if any
59 =item cdrtypenum - CDR type (see L<FS::cdr_type>) if any for this rate
61 =item region_group - Group in region group for rate plan
63 =item upstream_mult_charge - the multiplier to apply to the upstream price.
64 Defaults to zero, and should stay zero unless this rate is intended to include
65 a markup on pre-rated CDRs.
67 =item upstream_mult_cost - the multiplier to apply to the upstream price to
68 calculate the wholesale cost.
78 Creates a new call plan rate. To add the call plan rate to the database, see
81 Note that this stores the hash reference, not a distinct copy of the hash it
82 points to. You can ask the object for a copy with the I<hash> method.
86 # the new method can be inherited from FS::Record, if a table method is defined
88 sub table { 'rate_detail'; }
92 Adds this record to the database. If there is an error, returns the error,
93 otherwise returns false.
97 # the insert method can be inherited from FS::Record
101 Delete this record from the database.
105 # the delete method can be inherited from FS::Record
107 =item replace OLD_RECORD
109 Replaces the OLD_RECORD with this one in the database. If there is an error,
110 returns the error, otherwise returns false.
114 # the replace method can be inherited from FS::Record
118 Checks all fields to make sure this is a valid call plan rate. If there is
119 an error, returns the error, otherwise returns false. Called by the insert
124 # the check method should currently be supplied - FS::Record contains some
125 # data checking routines
131 $self->ut_numbern('ratedetailnum')
132 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
133 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
134 || $self->ut_foreign_keyn('dest_regionnum', 'rate_region', 'regionnum' )
135 || $self->ut_number('min_included')
137 #|| $self->ut_money('min_charge')
138 #good enough for now...
139 || $self->ut_floatn('conn_charge')
140 || $self->ut_floatn('conn_cost')
141 || $self->ut_float('min_charge')
142 || $self->ut_floatn('min_cost')
144 || $self->ut_number('sec_granularity')
146 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
147 || $self->ut_enum('region_group', [ '', 'Y' ])
149 || $self->ut_floatn('upstream_mult_charge')
150 || $self->ut_floatn('upstream_mult_cost')
152 return $error if $error;
159 Returns the parent call plan (see L<FS::rate>) associated with this call plan
164 Returns the origination region (see L<FS::rate_region>) associated with this
171 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
176 Returns the destination region (see L<FS::rate_region>) associated with this
183 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
186 =item dest_regionname
188 Returns the name of the destination region (see L<FS::rate_region>) associated
189 with this call plan rate.
193 sub dest_regionname {
195 my $dest_region = $self->dest_region;
196 $dest_region ? $dest_region->regionname : 'Global default';
199 =item dest_prefixes_short
201 Returns a short list of the prefixes for the destination region
202 (see L<FS::rate_region>) associated with this call plan rate.
206 sub dest_prefixes_short {
208 my $dest_region = $self->dest_region;
209 $dest_region ? $dest_region->prefixes_short : '';
214 Returns the L<FS::rate_time> object associated with this call
215 plan rate, if there is one.
221 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
226 Returns the I<ratetimename> field of the L<FS::rate_time> object
227 associated with this rate plan.
233 $self->ratetimenum ? $self->rate_time->ratetimename : '(default)';
238 Returns the name of the usage class (see L<FS::usage_class>) associated with
245 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
246 $usage_class ? $usage_class->classname : '';
251 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
252 rate, if there is one. If not, returns the cdrtypenum itself. This will
253 only return an empty string if cdrtypenum is NULL.
259 my $cdrtypenum = $self->cdrtypenum or return '';
260 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
261 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
272 Returns an (ordered) hash of granularity => name pairs
276 tie my %granularities, 'Tie::IxHash',
279 '30' => '30 second', # '1/2 minute',
290 Returns an (ordered) hash of conn_sec => name pairs
294 tie my %conn_secs, 'Tie::IxHash',
296 '1' => 'first second',
297 '6' => 'first 6 seconds',
298 '30' => 'first 30 seconds', # '1/2 minute',
299 '60' => 'first minute',
300 '120' => 'first 2 minutes',
301 '180' => 'first 3 minutes',
302 '300' => 'first 5 minutes',
309 =item process_edit_import
314 sub process_edit_import {
317 #do we actually belong in rate_detail, like 'table' says? even though we
318 # can possible create new rate records, that's a side effect, mostly we
319 # do edit rate_detail records in batch...
321 my $opt = { 'table' => 'rate_detail',
322 'params' => [], #required, apparantly
323 'formats' => { 'default' => [
332 my( $rate_detail, $g ) = @_;
333 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
334 $g = 60 if $g =~ /^\s*minute\s*$/i;
335 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
336 " for record ". Dumper($rate_detail);
337 $rate_detail->sec_granularity($1);
341 'format_headers' => { 'default' => 1, },
342 'format_types' => { 'default' => 'xls' },
346 #FS::Record::process_batch_import( $job, $opt, @_ );
348 my $table = $opt->{table};
349 my @pass_params = @{ $opt->{params} };
350 my %formats = %{ $opt->{formats} };
353 warn Dumper($param) if $DEBUG;
355 my $files = $param->{'uploaded_files'}
356 or die "No files provided.\n";
358 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
360 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
361 my $file = $dir. $files{'file'};
365 #FS::Record::batch_import( {
366 FS::rate_detail::edit_import( {
369 formats => \%formats,
370 format_types => $opt->{format_types},
371 format_headers => $opt->{format_headers},
372 format_sep_chars => $opt->{format_sep_chars},
373 format_fixedlength_formats => $opt->{format_fixedlength_formats},
378 format => $param->{format},
379 params => { map { $_ => $param->{$_} } @pass_params },
381 default_csv => $opt->{default_csv},
386 die "$error\n" if $error;
394 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
395 #could be turned into callbacks or something
400 warn "$me edit_import call with params: \n". Dumper($param)
403 my $table = $param->{table};
404 my $formats = $param->{formats};
406 my $job = $param->{job};
407 my $file = $param->{file};
408 my $format = $param->{'format'};
409 my $params = $param->{params} || {};
411 die "unknown format $format" unless exists $formats->{ $format };
413 my $type = $param->{'format_types'}
414 ? $param->{'format_types'}{ $format }
415 : $param->{type} || 'csv';
418 if ( $file =~ /\.(\w+)$/i ) {
422 warn "can't parse file type from filename $file; defaulting to CSV";
426 if $param->{'default_csv'} && $type ne 'xls';
429 my $header = $param->{'format_headers'}
430 ? $param->{'format_headers'}{ $param->{'format'} }
433 my $sep_char = $param->{'format_sep_chars'}
434 ? $param->{'format_sep_chars'}{ $param->{'format'} }
437 my $fixedlength_format =
438 $param->{'format_fixedlength_formats'}
439 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
442 my @fields = @{ $formats->{ $format } };
448 my @header = (); #edit_import
449 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
451 if ( $type eq 'csv' ) {
454 $attr{sep_char} = $sep_char if $sep_char;
455 $parser = new Text::CSV_XS \%attr;
457 } elsif ( $type eq 'fixedlength' ) {
459 eval "use Parse::FixedLength;";
461 $parser = new Parse::FixedLength $fixedlength_format;
464 die "Unknown file type $type\n";
467 @buffer = split(/\r?\n/, slurp($file) );
468 splice(@buffer, 0, ($header || 0) );
469 $count = scalar(@buffer);
471 } elsif ( $type eq 'xls' ) {
473 eval "use Spreadsheet::ParseExcel;";
476 eval "use DateTime::Format::Excel;";
477 #for now, just let the error be thrown if it is used, since only CDR
478 # formats bill_west and troop use it, not other excel-parsing things
481 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
483 $parser = $excel->{Worksheet}[0]; #first sheet
485 $count = $parser->{MaxRow} || $parser->{MinRow};
490 #edit_import - need some magic to parse the header
492 my @header_row = @{ $parser->{Cells}[$0] };
493 @header = map $_->{Val}, @header_row;
497 die "Unknown file type $type\n";
502 local $SIG{HUP} = 'IGNORE';
503 local $SIG{INT} = 'IGNORE';
504 local $SIG{QUIT} = 'IGNORE';
505 local $SIG{TERM} = 'IGNORE';
506 local $SIG{TSTP} = 'IGNORE';
507 local $SIG{PIPE} = 'IGNORE';
509 my $oldAutoCommit = $FS::UID::AutoCommit;
510 local $FS::UID::AutoCommit = 0;
513 #edit_import - use the header to setup looping over different rates
516 splice(@header,0,4); # # Region Country Prefixes
517 while ( my @next = splice(@header,0,4) ) {
519 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
520 $rate = qsearchs('rate', { 'ratenum' => $1 } )
521 or die "unknown ratenum $1";
522 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
523 $rate = new FS::rate { 'ratename' => $2 };
524 my $error = $rate->insert;
526 $dbh->rollback if $oldAutoCommit;
527 return "error inserting new rate: $error\n";
537 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
541 if ( $type eq 'csv' ) {
543 last unless scalar(@buffer);
544 $line = shift(@buffer);
546 $parser->parse($line) or do {
547 $dbh->rollback if $oldAutoCommit;
548 return "can't parse: ". $parser->error_input();
550 @columns = $parser->fields();
552 } elsif ( $type eq 'fixedlength' ) {
554 @columns = $parser->parse($line);
556 } elsif ( $type eq 'xls' ) {
558 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
559 || ! $parser->{Cells}[$row];
561 my @row = @{ $parser->{Cells}[$row] };
562 @columns = map $_->{Val}, @row;
565 #warn $z++. ": $_\n" for @columns;
568 die "Unknown file type $type\n";
573 my @repeat = @columns[0..3];
575 foreach my $rate ( @rate ) {
580 foreach my $field ( @fields ) {
582 my $value = shift @columns;
584 if ( ref($field) eq 'CODE' ) {
585 #&{$field}(\%hash, $value);
586 push @later, $field, $value;
588 } elsif ($field) { #edit_import
589 #??? $hash{$field} = $value if length($value);
590 $hash{$field} = $value if defined($value) && length($value);
595 unshift @columns, @repeat; #edit_import put these back on for next time
597 my $class = "FS::$table";
599 my $record = $class->new( \%hash );
601 $record->ratenum($rate->ratenum); #edit_import
603 #edit_improt n/a my $param = {};
604 while ( scalar(@later) ) {
605 my $sub = shift @later;
606 my $data = shift @later;
607 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
608 &{$sub}($record, $data); #edit_import - don't have $conf
609 #edit_import wrong loop last if exists( $param->{skiprow} );
611 #edit_import wrong loop next if exists( $param->{skiprow} );
613 #edit_import update or insert, not just insert
616 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
621 $record->ratedetailnum($old->ratedetailnum);
622 $error = $record->replace($old)
628 $dbh->rollback if $oldAutoCommit;
629 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
637 if ( $job && time - $min_sec > $last ) { #progress bar
638 $job->update_statustext( int(100 * $imported / $count) );
644 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
646 return "Empty file!" unless $imported || $param->{empty_ok};
658 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
659 schema.html from the base documentation.