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
71 Creates a new call plan rate. To add the call plan rate to the database, see
74 Note that this stores the hash reference, not a distinct copy of the hash it
75 points to. You can ask the object for a copy with the I<hash> method.
79 # the new method can be inherited from FS::Record, if a table method is defined
81 sub table { 'rate_detail'; }
85 Adds this record to the database. If there is an error, returns the error,
86 otherwise returns false.
90 # the insert method can be inherited from FS::Record
94 Delete this record from the database.
98 # the delete method can be inherited from FS::Record
100 =item replace OLD_RECORD
102 Replaces the OLD_RECORD with this one in the database. If there is an error,
103 returns the error, otherwise returns false.
107 # the replace method can be inherited from FS::Record
111 Checks all fields to make sure this is a valid call plan rate. If there is
112 an error, returns the error, otherwise returns false. Called by the insert
117 # the check method should currently be supplied - FS::Record contains some
118 # data checking routines
124 $self->ut_numbern('ratedetailnum')
125 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
126 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
127 || $self->ut_foreign_key('dest_regionnum', 'rate_region', 'regionnum' )
128 || $self->ut_number('min_included')
130 #|| $self->ut_money('min_charge')
131 #good enough for now...
132 || $self->ut_floatn('conn_charge')
133 || $self->ut_floatn('conn_cost')
134 || $self->ut_float('min_charge')
135 || $self->ut_floatn('min_cost')
137 || $self->ut_number('sec_granularity')
139 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
140 || $self->ut_enum('region_group', [ '', 'Y' ])
142 return $error if $error;
149 Returns the parent call plan (see L<FS::rate>) associated with this call plan
154 Returns the origination region (see L<FS::rate_region>) associated with this
161 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
166 Returns the destination region (see L<FS::rate_region>) associated with this
173 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
176 =item dest_regionname
178 Returns the name of the destination region (see L<FS::rate_region>) associated
179 with this call plan rate.
183 sub dest_regionname {
185 $self->dest_region->regionname;
188 =item dest_regionname
190 Returns a short list of the prefixes for the destination region
191 (see L<FS::rate_region>) associated with this call plan rate.
195 sub dest_prefixes_short {
197 $self->dest_region->prefixes_short;
202 Returns the L<FS::rate_time> object associated with this call
203 plan rate, if there is one.
209 $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
214 Returns the I<ratetimename> field of the L<FS::rate_time> object
215 associated with this rate plan.
221 $self->ratetimenum ? $self->rate_time->ratetimename : '(default)';
226 Returns the name of the usage class (see L<FS::usage_class>) associated with
233 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
234 $usage_class ? $usage_class->classname : '';
239 Returns the name of the CDR type (see L<FS::cdr_type) associated with this
240 rate, if there is one. If not, returns the cdrtypenum itself. This will
241 only return an empty string if cdrtypenum is NULL.
247 my $cdrtypenum = $self->cdrtypenum or return '';
248 my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
249 return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
260 Returns an (ordered) hash of granularity => name pairs
264 tie my %granularities, 'Tie::IxHash',
267 '30' => '30 second', # '1/2 minute',
278 Returns an (ordered) hash of conn_sec => name pairs
282 tie my %conn_secs, 'Tie::IxHash',
284 '1' => 'first second',
285 '6' => 'first 6 seconds',
286 '30' => 'first 30 seconds', # '1/2 minute',
287 '60' => 'first minute',
288 '120' => 'first 2 minutes',
289 '180' => 'first 3 minutes',
290 '300' => 'first 5 minutes',
297 =item process_edit_import
301 use Storable qw(thaw);
304 sub process_edit_import {
307 #do we actually belong in rate_detail, like 'table' says? even though we
308 # can possible create new rate records, that's a side effect, mostly we
309 # do edit rate_detail records in batch...
311 my $opt = { 'table' => 'rate_detail',
312 'params' => [], #required, apparantly
313 'formats' => { 'default' => [
322 my( $rate_detail, $g ) = @_;
323 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
324 $g = 60 if $g =~ /^\s*minute\s*$/i;
325 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
326 " for record ". Dumper($rate_detail);
327 $rate_detail->sec_granularity($1);
331 'format_headers' => { 'default' => 1, },
332 'format_types' => { 'default' => 'xls' },
336 #FS::Record::process_batch_import( $job, $opt, @_ );
338 my $table = $opt->{table};
339 my @pass_params = @{ $opt->{params} };
340 my %formats = %{ $opt->{formats} };
342 my $param = thaw(decode_base64(shift));
343 warn Dumper($param) if $DEBUG;
345 my $files = $param->{'uploaded_files'}
346 or die "No files provided.\n";
348 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
350 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
351 my $file = $dir. $files{'file'};
355 #FS::Record::batch_import( {
356 FS::rate_detail::edit_import( {
359 formats => \%formats,
360 format_types => $opt->{format_types},
361 format_headers => $opt->{format_headers},
362 format_sep_chars => $opt->{format_sep_chars},
363 format_fixedlength_formats => $opt->{format_fixedlength_formats},
368 format => $param->{format},
369 params => { map { $_ => $param->{$_} } @pass_params },
371 default_csv => $opt->{default_csv},
376 die "$error\n" if $error;
384 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
385 #could be turned into callbacks or something
390 warn "$me edit_import call with params: \n". Dumper($param)
393 my $table = $param->{table};
394 my $formats = $param->{formats};
396 my $job = $param->{job};
397 my $file = $param->{file};
398 my $format = $param->{'format'};
399 my $params = $param->{params} || {};
401 die "unknown format $format" unless exists $formats->{ $format };
403 my $type = $param->{'format_types'}
404 ? $param->{'format_types'}{ $format }
405 : $param->{type} || 'csv';
408 if ( $file =~ /\.(\w+)$/i ) {
412 warn "can't parse file type from filename $file; defaulting to CSV";
416 if $param->{'default_csv'} && $type ne 'xls';
419 my $header = $param->{'format_headers'}
420 ? $param->{'format_headers'}{ $param->{'format'} }
423 my $sep_char = $param->{'format_sep_chars'}
424 ? $param->{'format_sep_chars'}{ $param->{'format'} }
427 my $fixedlength_format =
428 $param->{'format_fixedlength_formats'}
429 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
432 my @fields = @{ $formats->{ $format } };
438 my @header = (); #edit_import
439 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
441 if ( $type eq 'csv' ) {
444 $attr{sep_char} = $sep_char if $sep_char;
445 $parser = new Text::CSV_XS \%attr;
447 } elsif ( $type eq 'fixedlength' ) {
449 eval "use Parse::FixedLength;";
451 $parser = new Parse::FixedLength $fixedlength_format;
454 die "Unknown file type $type\n";
457 @buffer = split(/\r?\n/, slurp($file) );
458 splice(@buffer, 0, ($header || 0) );
459 $count = scalar(@buffer);
461 } elsif ( $type eq 'xls' ) {
463 eval "use Spreadsheet::ParseExcel;";
466 eval "use DateTime::Format::Excel;";
467 #for now, just let the error be thrown if it is used, since only CDR
468 # formats bill_west and troop use it, not other excel-parsing things
471 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
473 $parser = $excel->{Worksheet}[0]; #first sheet
475 $count = $parser->{MaxRow} || $parser->{MinRow};
480 #edit_import - need some magic to parse the header
482 my @header_row = @{ $parser->{Cells}[$0] };
483 @header = map $_->{Val}, @header_row;
487 die "Unknown file type $type\n";
492 local $SIG{HUP} = 'IGNORE';
493 local $SIG{INT} = 'IGNORE';
494 local $SIG{QUIT} = 'IGNORE';
495 local $SIG{TERM} = 'IGNORE';
496 local $SIG{TSTP} = 'IGNORE';
497 local $SIG{PIPE} = 'IGNORE';
499 my $oldAutoCommit = $FS::UID::AutoCommit;
500 local $FS::UID::AutoCommit = 0;
503 #edit_import - use the header to setup looping over different rates
506 splice(@header,0,4); # # Region Country Prefixes
507 while ( my @next = splice(@header,0,4) ) {
509 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
510 $rate = qsearchs('rate', { 'ratenum' => $1 } )
511 or die "unknown ratenum $1";
512 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
513 $rate = new FS::rate { 'ratename' => $2 };
514 my $error = $rate->insert;
516 $dbh->rollback if $oldAutoCommit;
517 return "error inserting new rate: $error\n";
527 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
531 if ( $type eq 'csv' ) {
533 last unless scalar(@buffer);
534 $line = shift(@buffer);
536 $parser->parse($line) or do {
537 $dbh->rollback if $oldAutoCommit;
538 return "can't parse: ". $parser->error_input();
540 @columns = $parser->fields();
542 } elsif ( $type eq 'fixedlength' ) {
544 @columns = $parser->parse($line);
546 } elsif ( $type eq 'xls' ) {
548 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
549 || ! $parser->{Cells}[$row];
551 my @row = @{ $parser->{Cells}[$row] };
552 @columns = map $_->{Val}, @row;
555 #warn $z++. ": $_\n" for @columns;
558 die "Unknown file type $type\n";
563 my @repeat = @columns[0..3];
565 foreach my $rate ( @rate ) {
570 foreach my $field ( @fields ) {
572 my $value = shift @columns;
574 if ( ref($field) eq 'CODE' ) {
575 #&{$field}(\%hash, $value);
576 push @later, $field, $value;
578 } elsif ($field) { #edit_import
579 #??? $hash{$field} = $value if length($value);
580 $hash{$field} = $value if defined($value) && length($value);
585 unshift @columns, @repeat; #edit_import put these back on for next time
587 my $class = "FS::$table";
589 my $record = $class->new( \%hash );
591 $record->ratenum($rate->ratenum); #edit_import
593 #edit_improt n/a my $param = {};
594 while ( scalar(@later) ) {
595 my $sub = shift @later;
596 my $data = shift @later;
597 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
598 &{$sub}($record, $data); #edit_import - don't have $conf
599 #edit_import wrong loop last if exists( $param->{skiprow} );
601 #edit_import wrong loop next if exists( $param->{skiprow} );
603 #edit_import update or insert, not just insert
606 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
611 $record->ratedetailnum($old->ratedetailnum);
612 $error = $record->replace($old)
618 $dbh->rollback if $oldAutoCommit;
619 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
627 if ( $job && time - $min_sec > $last ) { #progress bar
628 $job->update_statustext( int(100 * $imported / $count) );
634 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
636 return "Empty file!" unless $imported || $param->{empty_ok};
648 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
649 schema.html from the base documentation.