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',
235 use Storable qw(thaw);
238 sub process_edit_import {
241 #do we actually belong in rate_detail, like 'table' says? even though we
242 # can possible create new rate records, that's a side effect, mostly we
243 # do edit rate_detail records in batch...
245 my $opt = { 'table' => 'rate_detail',
246 'params' => [], #required, apparantly
247 'formats' => { 'default' => [
256 my( $rate_detail, $g ) = @_;
257 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
258 $g = 60 if $g =~ /^\s*minute\s*$/i;
259 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
260 " for record ". Dumper($rate_detail);
261 $rate_detail->sec_granularity($1);
265 'format_headers' => { 'default' => 1, },
266 'format_types' => { 'default' => 'xls' },
270 #FS::Record::process_batch_import( $job, $opt, @_ );
272 my $table = $opt->{table};
273 my @pass_params = @{ $opt->{params} };
274 my %formats = %{ $opt->{formats} };
276 my $param = thaw(decode_base64(shift));
277 warn Dumper($param) if $DEBUG;
279 my $files = $param->{'uploaded_files'}
280 or die "No files provided.\n";
282 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
284 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
285 my $file = $dir. $files{'file'};
289 #FS::Record::batch_import( {
290 FS::rate_detail::edit_import( {
293 formats => \%formats,
294 format_types => $opt->{format_types},
295 format_headers => $opt->{format_headers},
296 format_sep_chars => $opt->{format_sep_chars},
297 format_fixedlength_formats => $opt->{format_fixedlength_formats},
302 format => $param->{format},
303 params => { map { $_ => $param->{$_} } @pass_params },
305 default_csv => $opt->{default_csv},
310 die "$error\n" if $error;
314 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
315 #could be turned into callbacks or something
320 warn "$me edit_import call with params: \n". Dumper($param)
323 my $table = $param->{table};
324 my $formats = $param->{formats};
326 my $job = $param->{job};
327 my $file = $param->{file};
328 my $format = $param->{'format'};
329 my $params = $param->{params} || {};
331 die "unknown format $format" unless exists $formats->{ $format };
333 my $type = $param->{'format_types'}
334 ? $param->{'format_types'}{ $format }
335 : $param->{type} || 'csv';
338 if ( $file =~ /\.(\w+)$/i ) {
342 warn "can't parse file type from filename $file; defaulting to CSV";
346 if $param->{'default_csv'} && $type ne 'xls';
349 my $header = $param->{'format_headers'}
350 ? $param->{'format_headers'}{ $param->{'format'} }
353 my $sep_char = $param->{'format_sep_chars'}
354 ? $param->{'format_sep_chars'}{ $param->{'format'} }
357 my $fixedlength_format =
358 $param->{'format_fixedlength_formats'}
359 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
362 my @fields = @{ $formats->{ $format } };
368 my @header = (); #edit_import
369 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
371 if ( $type eq 'csv' ) {
374 $attr{sep_char} = $sep_char if $sep_char;
375 $parser = new Text::CSV_XS \%attr;
377 } elsif ( $type eq 'fixedlength' ) {
379 eval "use Parse::FixedLength;";
381 $parser = new Parse::FixedLength $fixedlength_format;
384 die "Unknown file type $type\n";
387 @buffer = split(/\r?\n/, slurp($file) );
388 splice(@buffer, 0, ($header || 0) );
389 $count = scalar(@buffer);
391 } elsif ( $type eq 'xls' ) {
393 eval "use Spreadsheet::ParseExcel;";
396 eval "use DateTime::Format::Excel;";
397 #for now, just let the error be thrown if it is used, since only CDR
398 # formats bill_west and troop use it, not other excel-parsing things
401 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
403 $parser = $excel->{Worksheet}[0]; #first sheet
405 $count = $parser->{MaxRow} || $parser->{MinRow};
410 #edit_import - need some magic to parse the header
412 my @header_row = @{ $parser->{Cells}[$0] };
413 @header = map $_->{Val}, @header_row;
417 die "Unknown file type $type\n";
422 local $SIG{HUP} = 'IGNORE';
423 local $SIG{INT} = 'IGNORE';
424 local $SIG{QUIT} = 'IGNORE';
425 local $SIG{TERM} = 'IGNORE';
426 local $SIG{TSTP} = 'IGNORE';
427 local $SIG{PIPE} = 'IGNORE';
429 my $oldAutoCommit = $FS::UID::AutoCommit;
430 local $FS::UID::AutoCommit = 0;
433 #edit_import - use the header to setup looping over different rates
436 splice(@header,0,4); # # Region Country Prefixes
437 while ( my @next = splice(@header,0,4) ) {
439 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
440 $rate = qsearchs('rate', { 'ratenum' => $1 } )
441 or die "unknown ratenum $1";
442 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
443 $rate = new FS::rate { 'ratename' => $2 };
444 my $error = $rate->insert;
446 $dbh->rollback if $oldAutoCommit;
447 return "error inserting new rate: $error\n";
457 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
461 if ( $type eq 'csv' ) {
463 last unless scalar(@buffer);
464 $line = shift(@buffer);
466 $parser->parse($line) or do {
467 $dbh->rollback if $oldAutoCommit;
468 return "can't parse: ". $parser->error_input();
470 @columns = $parser->fields();
472 } elsif ( $type eq 'fixedlength' ) {
474 @columns = $parser->parse($line);
476 } elsif ( $type eq 'xls' ) {
478 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
479 || ! $parser->{Cells}[$row];
481 my @row = @{ $parser->{Cells}[$row] };
482 @columns = map $_->{Val}, @row;
485 #warn $z++. ": $_\n" for @columns;
488 die "Unknown file type $type\n";
493 my @repeat = @columns[0..3];
495 foreach my $rate ( @rate ) {
500 foreach my $field ( @fields ) {
502 my $value = shift @columns;
504 if ( ref($field) eq 'CODE' ) {
505 #&{$field}(\%hash, $value);
506 push @later, $field, $value;
508 } elsif ($field) { #edit_import
509 #??? $hash{$field} = $value if length($value);
510 $hash{$field} = $value if defined($value) && length($value);
515 unshift @columns, @repeat; #edit_import put these back on for next time
517 my $class = "FS::$table";
519 my $record = $class->new( \%hash );
521 $record->ratenum($rate->ratenum); #edit_import
523 #edit_improt n/a my $param = {};
524 while ( scalar(@later) ) {
525 my $sub = shift @later;
526 my $data = shift @later;
527 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
528 &{$sub}($record, $data); #edit_import - don't have $conf
529 #edit_import wrong loop last if exists( $param->{skiprow} );
531 #edit_import wrong loop next if exists( $param->{skiprow} );
533 #edit_import update or insert, not just insert
536 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
541 $record->ratedetailnum($old->ratedetailnum);
542 $error = $record->replace($old)
548 $dbh->rollback if $oldAutoCommit;
549 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
557 if ( $job && time - $min_sec > $last ) { #progress bar
558 $job->update_statustext( int(100 * $imported / $count) );
564 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
566 return "Empty file!" unless $imported || $param->{empty_ok};
580 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
581 schema.html from the base documentation.