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_floatn('conn_charge')
134 || $self->ut_floatn('conn_cost')
135 || $self->ut_float('min_charge')
136 || $self->ut_floatn('min_cost')
138 || $self->ut_number('sec_granularity')
140 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
141 || $self->ut_enum('region_group', [ '', 'Y' ])
143 return $error if $error;
150 Returns the parent call plan (see L<FS::rate>) associated with this call plan
157 qsearchs('rate', { 'ratenum' => $self->ratenum } );
162 Returns the origination region (see L<FS::rate_region>) associated with this
169 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
174 Returns the destination region (see L<FS::rate_region>) associated with this
181 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
184 =item dest_regionname
186 Returns the name of the destination region (see L<FS::rate_region>) associated
187 with this call plan rate.
191 sub dest_regionname {
193 $self->dest_region->regionname;
196 =item dest_regionname
198 Returns a short list of the prefixes for the destination region
199 (see L<FS::rate_region>) associated with this call plan rate.
203 sub dest_prefixes_short {
205 $self->dest_region->prefixes_short;
210 Returns the L<FS::rate_time> object associated with this call
211 plan rate, if there is one.
217 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
222 Returns the I<ratetimename> field of the L<FS::rate_time> object
223 associated with this rate plan.
229 $self->ratetimenum ? $self->rate_time->ratetimename : '(default)';
234 Returns the name of the usage class (see L<FS::usage_class>) associated with
241 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
242 $usage_class ? $usage_class->classname : '';
247 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
248 rate, if there is one. If not, returns the cdrtypenum itself. This will
249 only return an empty string if cdrtypenum is NULL.
255 my $cdrtypenum = $self->cdrtypenum or return '';
256 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
257 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
268 Returns an (ordered) hash of granularity => name pairs
272 tie my %granularities, 'Tie::IxHash',
275 '30' => '30 second', # '1/2 minute',
286 Returns an (ordered) hash of conn_sec => name pairs
290 tie my %conn_secs, 'Tie::IxHash',
292 '1' => 'first second',
293 '6' => 'first 6 seconds',
294 '30' => 'first 30 seconds', # '1/2 minute',
295 '60' => 'first minute',
296 '120' => 'first 2 minutes',
297 '180' => 'first 3 minutes',
298 '300' => 'first 5 minutes',
305 =item process_edit_import
309 use Storable qw(thaw);
312 sub process_edit_import {
315 #do we actually belong in rate_detail, like 'table' says? even though we
316 # can possible create new rate records, that's a side effect, mostly we
317 # do edit rate_detail records in batch...
319 my $opt = { 'table' => 'rate_detail',
320 'params' => [], #required, apparantly
321 'formats' => { 'default' => [
330 my( $rate_detail, $g ) = @_;
331 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
332 $g = 60 if $g =~ /^\s*minute\s*$/i;
333 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
334 " for record ". Dumper($rate_detail);
335 $rate_detail->sec_granularity($1);
339 'format_headers' => { 'default' => 1, },
340 'format_types' => { 'default' => 'xls' },
344 #FS::Record::process_batch_import( $job, $opt, @_ );
346 my $table = $opt->{table};
347 my @pass_params = @{ $opt->{params} };
348 my %formats = %{ $opt->{formats} };
350 my $param = thaw(decode_base64(shift));
351 warn Dumper($param) if $DEBUG;
353 my $files = $param->{'uploaded_files'}
354 or die "No files provided.\n";
356 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
358 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
359 my $file = $dir. $files{'file'};
363 #FS::Record::batch_import( {
364 FS::rate_detail::edit_import( {
367 formats => \%formats,
368 format_types => $opt->{format_types},
369 format_headers => $opt->{format_headers},
370 format_sep_chars => $opt->{format_sep_chars},
371 format_fixedlength_formats => $opt->{format_fixedlength_formats},
376 format => $param->{format},
377 params => { map { $_ => $param->{$_} } @pass_params },
379 default_csv => $opt->{default_csv},
384 die "$error\n" if $error;
392 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
393 #could be turned into callbacks or something
398 warn "$me edit_import call with params: \n". Dumper($param)
401 my $table = $param->{table};
402 my $formats = $param->{formats};
404 my $job = $param->{job};
405 my $file = $param->{file};
406 my $format = $param->{'format'};
407 my $params = $param->{params} || {};
409 die "unknown format $format" unless exists $formats->{ $format };
411 my $type = $param->{'format_types'}
412 ? $param->{'format_types'}{ $format }
413 : $param->{type} || 'csv';
416 if ( $file =~ /\.(\w+)$/i ) {
420 warn "can't parse file type from filename $file; defaulting to CSV";
424 if $param->{'default_csv'} && $type ne 'xls';
427 my $header = $param->{'format_headers'}
428 ? $param->{'format_headers'}{ $param->{'format'} }
431 my $sep_char = $param->{'format_sep_chars'}
432 ? $param->{'format_sep_chars'}{ $param->{'format'} }
435 my $fixedlength_format =
436 $param->{'format_fixedlength_formats'}
437 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
440 my @fields = @{ $formats->{ $format } };
446 my @header = (); #edit_import
447 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
449 if ( $type eq 'csv' ) {
452 $attr{sep_char} = $sep_char if $sep_char;
453 $parser = new Text::CSV_XS \%attr;
455 } elsif ( $type eq 'fixedlength' ) {
457 eval "use Parse::FixedLength;";
459 $parser = new Parse::FixedLength $fixedlength_format;
462 die "Unknown file type $type\n";
465 @buffer = split(/\r?\n/, slurp($file) );
466 splice(@buffer, 0, ($header || 0) );
467 $count = scalar(@buffer);
469 } elsif ( $type eq 'xls' ) {
471 eval "use Spreadsheet::ParseExcel;";
474 eval "use DateTime::Format::Excel;";
475 #for now, just let the error be thrown if it is used, since only CDR
476 # formats bill_west and troop use it, not other excel-parsing things
479 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
481 $parser = $excel->{Worksheet}[0]; #first sheet
483 $count = $parser->{MaxRow} || $parser->{MinRow};
488 #edit_import - need some magic to parse the header
490 my @header_row = @{ $parser->{Cells}[$0] };
491 @header = map $_->{Val}, @header_row;
495 die "Unknown file type $type\n";
500 local $SIG{HUP} = 'IGNORE';
501 local $SIG{INT} = 'IGNORE';
502 local $SIG{QUIT} = 'IGNORE';
503 local $SIG{TERM} = 'IGNORE';
504 local $SIG{TSTP} = 'IGNORE';
505 local $SIG{PIPE} = 'IGNORE';
507 my $oldAutoCommit = $FS::UID::AutoCommit;
508 local $FS::UID::AutoCommit = 0;
511 #edit_import - use the header to setup looping over different rates
514 splice(@header,0,4); # # Region Country Prefixes
515 while ( my @next = splice(@header,0,4) ) {
517 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
518 $rate = qsearchs('rate', { 'ratenum' => $1 } )
519 or die "unknown ratenum $1";
520 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
521 $rate = new FS::rate { 'ratename' => $2 };
522 my $error = $rate->insert;
524 $dbh->rollback if $oldAutoCommit;
525 return "error inserting new rate: $error\n";
535 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
539 if ( $type eq 'csv' ) {
541 last unless scalar(@buffer);
542 $line = shift(@buffer);
544 $parser->parse($line) or do {
545 $dbh->rollback if $oldAutoCommit;
546 return "can't parse: ". $parser->error_input();
548 @columns = $parser->fields();
550 } elsif ( $type eq 'fixedlength' ) {
552 @columns = $parser->parse($line);
554 } elsif ( $type eq 'xls' ) {
556 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
557 || ! $parser->{Cells}[$row];
559 my @row = @{ $parser->{Cells}[$row] };
560 @columns = map $_->{Val}, @row;
563 #warn $z++. ": $_\n" for @columns;
566 die "Unknown file type $type\n";
571 my @repeat = @columns[0..3];
573 foreach my $rate ( @rate ) {
578 foreach my $field ( @fields ) {
580 my $value = shift @columns;
582 if ( ref($field) eq 'CODE' ) {
583 #&{$field}(\%hash, $value);
584 push @later, $field, $value;
586 } elsif ($field) { #edit_import
587 #??? $hash{$field} = $value if length($value);
588 $hash{$field} = $value if defined($value) && length($value);
593 unshift @columns, @repeat; #edit_import put these back on for next time
595 my $class = "FS::$table";
597 my $record = $class->new( \%hash );
599 $record->ratenum($rate->ratenum); #edit_import
601 #edit_improt n/a my $param = {};
602 while ( scalar(@later) ) {
603 my $sub = shift @later;
604 my $data = shift @later;
605 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
606 &{$sub}($record, $data); #edit_import - don't have $conf
607 #edit_import wrong loop last if exists( $param->{skiprow} );
609 #edit_import wrong loop next if exists( $param->{skiprow} );
611 #edit_import update or insert, not just insert
614 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
619 $record->ratedetailnum($old->ratedetailnum);
620 $error = $record->replace($old)
626 $dbh->rollback if $oldAutoCommit;
627 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
635 if ( $job && time - $min_sec > $last ) { #progress bar
636 $job->update_statustext( int(100 * $imported / $count) );
642 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
644 return "Empty file!" unless $imported || $param->{empty_ok};
656 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
657 schema.html from the base documentation.