1 package FS::rate_detail;
4 use vars qw( @ISA $DEBUG $me );
5 use FS::Record qw( qsearch qsearchs dbh );
10 @ISA = qw(FS::Record);
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
65 Creates a new call plan rate. To add the call plan rate to the database, see
68 Note that this stores the hash reference, not a distinct copy of the hash it
69 points to. You can ask the object for a copy with the I<hash> method.
73 # the new method can be inherited from FS::Record, if a table method is defined
75 sub table { 'rate_detail'; }
79 Adds this record to the database. If there is an error, returns the error,
80 otherwise returns false.
84 # the insert method can be inherited from FS::Record
88 Delete this record from the database.
92 # the delete method can be inherited from FS::Record
94 =item replace OLD_RECORD
96 Replaces the OLD_RECORD with this one in the database. If there is an error,
97 returns the error, otherwise returns false.
101 # the replace method can be inherited from FS::Record
105 Checks all fields to make sure this is a valid call plan rate. If there is
106 an error, returns the error, otherwise returns false. Called by the insert
111 # the check method should currently be supplied - FS::Record contains some
112 # data checking routines
118 $self->ut_numbern('ratedetailnum')
119 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
120 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
121 || $self->ut_foreign_key('dest_regionnum', 'rate_region', 'regionnum' )
122 || $self->ut_number('min_included')
124 #|| $self->ut_money('min_charge')
125 #good enough for now...
126 || $self->ut_float('min_charge')
128 || $self->ut_number('sec_granularity')
130 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
132 return $error if $error;
139 Returns the parent call plan (see L<FS::rate>) associated with this call plan
146 qsearchs('rate', { 'ratenum' => $self->ratenum } );
151 Returns the origination region (see L<FS::rate_region>) associated with this
158 qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
163 Returns the destination region (see L<FS::rate_region>) associated with this
170 qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
173 =item dest_regionname
175 Returns the name of the destination region (see L<FS::rate_region>) associated
176 with this call plan rate.
180 sub dest_regionname {
182 $self->dest_region->regionname;
185 =item dest_regionname
187 Returns a short list of the prefixes for the destination region
188 (see L<FS::rate_region>) associated with this call plan rate.
192 sub dest_prefixes_short {
194 $self->dest_region->prefixes_short;
199 Returns the name of the usage class (see L<FS::usage_class>) associated with
206 my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
207 $usage_class ? $usage_class->classname : '';
219 Returns an (ordered) hash of granularity => name pairs
223 tie my %granularities, 'Tie::IxHash',
226 '30' => '30 second', # '1/2 minute',
237 Returns an (ordered) hash of conn_sec => name pairs
241 tie my %conn_secs, 'Tie::IxHash',
243 '1' => 'first second',
244 '6' => 'first 6 seconds',
245 '30' => 'first 30 seconds', # '1/2 minute',
246 '60' => 'first minute',
247 '120' => 'first 2 minutes',
248 '180' => 'first 3 minutes',
249 '300' => 'first 5 minutes',
256 =item process_edit_import
260 use Storable qw(thaw);
263 sub process_edit_import {
266 #do we actually belong in rate_detail, like 'table' says? even though we
267 # can possible create new rate records, that's a side effect, mostly we
268 # do edit rate_detail records in batch...
270 my $opt = { 'table' => 'rate_detail',
271 'params' => [], #required, apparantly
272 'formats' => { 'default' => [
281 my( $rate_detail, $g ) = @_;
282 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
283 $g = 60 if $g =~ /^\s*minute\s*$/i;
284 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
285 " for record ". Dumper($rate_detail);
286 $rate_detail->sec_granularity($1);
290 'format_headers' => { 'default' => 1, },
291 'format_types' => { 'default' => 'xls' },
295 #FS::Record::process_batch_import( $job, $opt, @_ );
297 my $table = $opt->{table};
298 my @pass_params = @{ $opt->{params} };
299 my %formats = %{ $opt->{formats} };
301 my $param = thaw(decode_base64(shift));
302 warn Dumper($param) if $DEBUG;
304 my $files = $param->{'uploaded_files'}
305 or die "No files provided.\n";
307 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
309 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
310 my $file = $dir. $files{'file'};
314 #FS::Record::batch_import( {
315 FS::rate_detail::edit_import( {
318 formats => \%formats,
319 format_types => $opt->{format_types},
320 format_headers => $opt->{format_headers},
321 format_sep_chars => $opt->{format_sep_chars},
322 format_fixedlength_formats => $opt->{format_fixedlength_formats},
327 format => $param->{format},
328 params => { map { $_ => $param->{$_} } @pass_params },
330 default_csv => $opt->{default_csv},
335 die "$error\n" if $error;
343 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
344 #could be turned into callbacks or something
349 warn "$me edit_import call with params: \n". Dumper($param)
352 my $table = $param->{table};
353 my $formats = $param->{formats};
355 my $job = $param->{job};
356 my $file = $param->{file};
357 my $format = $param->{'format'};
358 my $params = $param->{params} || {};
360 die "unknown format $format" unless exists $formats->{ $format };
362 my $type = $param->{'format_types'}
363 ? $param->{'format_types'}{ $format }
364 : $param->{type} || 'csv';
367 if ( $file =~ /\.(\w+)$/i ) {
371 warn "can't parse file type from filename $file; defaulting to CSV";
375 if $param->{'default_csv'} && $type ne 'xls';
378 my $header = $param->{'format_headers'}
379 ? $param->{'format_headers'}{ $param->{'format'} }
382 my $sep_char = $param->{'format_sep_chars'}
383 ? $param->{'format_sep_chars'}{ $param->{'format'} }
386 my $fixedlength_format =
387 $param->{'format_fixedlength_formats'}
388 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
391 my @fields = @{ $formats->{ $format } };
397 my @header = (); #edit_import
398 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
400 if ( $type eq 'csv' ) {
403 $attr{sep_char} = $sep_char if $sep_char;
404 $parser = new Text::CSV_XS \%attr;
406 } elsif ( $type eq 'fixedlength' ) {
408 eval "use Parse::FixedLength;";
410 $parser = new Parse::FixedLength $fixedlength_format;
413 die "Unknown file type $type\n";
416 @buffer = split(/\r?\n/, slurp($file) );
417 splice(@buffer, 0, ($header || 0) );
418 $count = scalar(@buffer);
420 } elsif ( $type eq 'xls' ) {
422 eval "use Spreadsheet::ParseExcel;";
425 eval "use DateTime::Format::Excel;";
426 #for now, just let the error be thrown if it is used, since only CDR
427 # formats bill_west and troop use it, not other excel-parsing things
430 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
432 $parser = $excel->{Worksheet}[0]; #first sheet
434 $count = $parser->{MaxRow} || $parser->{MinRow};
439 #edit_import - need some magic to parse the header
441 my @header_row = @{ $parser->{Cells}[$0] };
442 @header = map $_->{Val}, @header_row;
446 die "Unknown file type $type\n";
451 local $SIG{HUP} = 'IGNORE';
452 local $SIG{INT} = 'IGNORE';
453 local $SIG{QUIT} = 'IGNORE';
454 local $SIG{TERM} = 'IGNORE';
455 local $SIG{TSTP} = 'IGNORE';
456 local $SIG{PIPE} = 'IGNORE';
458 my $oldAutoCommit = $FS::UID::AutoCommit;
459 local $FS::UID::AutoCommit = 0;
462 #edit_import - use the header to setup looping over different rates
465 splice(@header,0,4); # # Region Country Prefixes
466 while ( my @next = splice(@header,0,4) ) {
468 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
469 $rate = qsearchs('rate', { 'ratenum' => $1 } )
470 or die "unknown ratenum $1";
471 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
472 $rate = new FS::rate { 'ratename' => $2 };
473 my $error = $rate->insert;
475 $dbh->rollback if $oldAutoCommit;
476 return "error inserting new rate: $error\n";
486 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
490 if ( $type eq 'csv' ) {
492 last unless scalar(@buffer);
493 $line = shift(@buffer);
495 $parser->parse($line) or do {
496 $dbh->rollback if $oldAutoCommit;
497 return "can't parse: ". $parser->error_input();
499 @columns = $parser->fields();
501 } elsif ( $type eq 'fixedlength' ) {
503 @columns = $parser->parse($line);
505 } elsif ( $type eq 'xls' ) {
507 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
508 || ! $parser->{Cells}[$row];
510 my @row = @{ $parser->{Cells}[$row] };
511 @columns = map $_->{Val}, @row;
514 #warn $z++. ": $_\n" for @columns;
517 die "Unknown file type $type\n";
522 my @repeat = @columns[0..3];
524 foreach my $rate ( @rate ) {
529 foreach my $field ( @fields ) {
531 my $value = shift @columns;
533 if ( ref($field) eq 'CODE' ) {
534 #&{$field}(\%hash, $value);
535 push @later, $field, $value;
537 } elsif ($field) { #edit_import
538 #??? $hash{$field} = $value if length($value);
539 $hash{$field} = $value if defined($value) && length($value);
544 unshift @columns, @repeat; #edit_import put these back on for next time
546 my $class = "FS::$table";
548 my $record = $class->new( \%hash );
550 $record->ratenum($rate->ratenum); #edit_import
552 #edit_improt n/a my $param = {};
553 while ( scalar(@later) ) {
554 my $sub = shift @later;
555 my $data = shift @later;
556 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
557 &{$sub}($record, $data); #edit_import - don't have $conf
558 #edit_import wrong loop last if exists( $param->{skiprow} );
560 #edit_import wrong loop next if exists( $param->{skiprow} );
562 #edit_import update or insert, not just insert
565 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
570 $record->ratedetailnum($old->ratedetailnum);
571 $error = $record->replace($old)
577 $dbh->rollback if $oldAutoCommit;
578 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
586 if ( $job && time - $min_sec > $last ) { #progress bar
587 $job->update_statustext( int(100 * $imported / $count) );
593 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
595 return "Empty file!" unless $imported || $param->{empty_ok};
607 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
608 schema.html from the base documentation.