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
68 Creates a new call plan rate. To add the call plan rate to the database, see
71 Note that this stores the hash reference, not a distinct copy of the hash it
72 points to. You can ask the object for a copy with the I<hash> method.
76 # the new method can be inherited from FS::Record, if a table method is defined
78 sub table { 'rate_detail'; }
82 Adds this record to the database. If there is an error, returns the error,
83 otherwise returns false.
87 # the insert method can be inherited from FS::Record
91 Delete this record from the database.
95 # the delete method can be inherited from FS::Record
97 =item replace OLD_RECORD
99 Replaces the OLD_RECORD with this one in the database. If there is an error,
100 returns the error, otherwise returns false.
104 # the replace method can be inherited from FS::Record
108 Checks all fields to make sure this is a valid call plan rate. If there is
109 an error, returns the error, otherwise returns false. Called by the insert
114 # the check method should currently be supplied - FS::Record contains some
115 # data checking routines
121 $self->ut_numbern('ratedetailnum')
122 || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
123 || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
124 || $self->ut_foreign_key('dest_regionnum', 'rate_region', 'regionnum' )
125 || $self->ut_number('min_included')
127 #|| $self->ut_money('min_charge')
128 #good enough for now...
129 || $self->ut_float('min_charge')
131 || $self->ut_number('sec_granularity')
133 || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
135 return $error if $error;
142 Returns the parent call plan (see L<FS::rate>) associated with this call plan
149 qsearchs('rate', { 'ratenum' => $self->ratenum } );
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 : '';
246 Returns an (ordered) hash of granularity => name pairs
250 tie my %granularities, 'Tie::IxHash',
253 '30' => '30 second', # '1/2 minute',
264 Returns an (ordered) hash of conn_sec => name pairs
268 tie my %conn_secs, 'Tie::IxHash',
270 '1' => 'first second',
271 '6' => 'first 6 seconds',
272 '30' => 'first 30 seconds', # '1/2 minute',
273 '60' => 'first minute',
274 '120' => 'first 2 minutes',
275 '180' => 'first 3 minutes',
276 '300' => 'first 5 minutes',
283 =item process_edit_import
287 use Storable qw(thaw);
290 sub process_edit_import {
293 #do we actually belong in rate_detail, like 'table' says? even though we
294 # can possible create new rate records, that's a side effect, mostly we
295 # do edit rate_detail records in batch...
297 my $opt = { 'table' => 'rate_detail',
298 'params' => [], #required, apparantly
299 'formats' => { 'default' => [
308 my( $rate_detail, $g ) = @_;
309 $g = 0 if $g =~ /^\s*(per-)?call\s*$/i;
310 $g = 60 if $g =~ /^\s*minute\s*$/i;
311 $g =~ /^(\d+)/ or die "can't parse granularity: $g".
312 " for record ". Dumper($rate_detail);
313 $rate_detail->sec_granularity($1);
317 'format_headers' => { 'default' => 1, },
318 'format_types' => { 'default' => 'xls' },
322 #FS::Record::process_batch_import( $job, $opt, @_ );
324 my $table = $opt->{table};
325 my @pass_params = @{ $opt->{params} };
326 my %formats = %{ $opt->{formats} };
328 my $param = thaw(decode_base64(shift));
329 warn Dumper($param) if $DEBUG;
331 my $files = $param->{'uploaded_files'}
332 or die "No files provided.\n";
334 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
336 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
337 my $file = $dir. $files{'file'};
341 #FS::Record::batch_import( {
342 FS::rate_detail::edit_import( {
345 formats => \%formats,
346 format_types => $opt->{format_types},
347 format_headers => $opt->{format_headers},
348 format_sep_chars => $opt->{format_sep_chars},
349 format_fixedlength_formats => $opt->{format_fixedlength_formats},
354 format => $param->{format},
355 params => { map { $_ => $param->{$_} } @pass_params },
357 default_csv => $opt->{default_csv},
362 die "$error\n" if $error;
370 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
371 #could be turned into callbacks or something
376 warn "$me edit_import call with params: \n". Dumper($param)
379 my $table = $param->{table};
380 my $formats = $param->{formats};
382 my $job = $param->{job};
383 my $file = $param->{file};
384 my $format = $param->{'format'};
385 my $params = $param->{params} || {};
387 die "unknown format $format" unless exists $formats->{ $format };
389 my $type = $param->{'format_types'}
390 ? $param->{'format_types'}{ $format }
391 : $param->{type} || 'csv';
394 if ( $file =~ /\.(\w+)$/i ) {
398 warn "can't parse file type from filename $file; defaulting to CSV";
402 if $param->{'default_csv'} && $type ne 'xls';
405 my $header = $param->{'format_headers'}
406 ? $param->{'format_headers'}{ $param->{'format'} }
409 my $sep_char = $param->{'format_sep_chars'}
410 ? $param->{'format_sep_chars'}{ $param->{'format'} }
413 my $fixedlength_format =
414 $param->{'format_fixedlength_formats'}
415 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
418 my @fields = @{ $formats->{ $format } };
424 my @header = (); #edit_import
425 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
427 if ( $type eq 'csv' ) {
430 $attr{sep_char} = $sep_char if $sep_char;
431 $parser = new Text::CSV_XS \%attr;
433 } elsif ( $type eq 'fixedlength' ) {
435 eval "use Parse::FixedLength;";
437 $parser = new Parse::FixedLength $fixedlength_format;
440 die "Unknown file type $type\n";
443 @buffer = split(/\r?\n/, slurp($file) );
444 splice(@buffer, 0, ($header || 0) );
445 $count = scalar(@buffer);
447 } elsif ( $type eq 'xls' ) {
449 eval "use Spreadsheet::ParseExcel;";
452 eval "use DateTime::Format::Excel;";
453 #for now, just let the error be thrown if it is used, since only CDR
454 # formats bill_west and troop use it, not other excel-parsing things
457 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
459 $parser = $excel->{Worksheet}[0]; #first sheet
461 $count = $parser->{MaxRow} || $parser->{MinRow};
466 #edit_import - need some magic to parse the header
468 my @header_row = @{ $parser->{Cells}[$0] };
469 @header = map $_->{Val}, @header_row;
473 die "Unknown file type $type\n";
478 local $SIG{HUP} = 'IGNORE';
479 local $SIG{INT} = 'IGNORE';
480 local $SIG{QUIT} = 'IGNORE';
481 local $SIG{TERM} = 'IGNORE';
482 local $SIG{TSTP} = 'IGNORE';
483 local $SIG{PIPE} = 'IGNORE';
485 my $oldAutoCommit = $FS::UID::AutoCommit;
486 local $FS::UID::AutoCommit = 0;
489 #edit_import - use the header to setup looping over different rates
492 splice(@header,0,4); # # Region Country Prefixes
493 while ( my @next = splice(@header,0,4) ) {
495 if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
496 $rate = qsearchs('rate', { 'ratenum' => $1 } )
497 or die "unknown ratenum $1";
498 } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
499 $rate = new FS::rate { 'ratename' => $2 };
500 my $error = $rate->insert;
502 $dbh->rollback if $oldAutoCommit;
503 return "error inserting new rate: $error\n";
513 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
517 if ( $type eq 'csv' ) {
519 last unless scalar(@buffer);
520 $line = shift(@buffer);
522 $parser->parse($line) or do {
523 $dbh->rollback if $oldAutoCommit;
524 return "can't parse: ". $parser->error_input();
526 @columns = $parser->fields();
528 } elsif ( $type eq 'fixedlength' ) {
530 @columns = $parser->parse($line);
532 } elsif ( $type eq 'xls' ) {
534 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
535 || ! $parser->{Cells}[$row];
537 my @row = @{ $parser->{Cells}[$row] };
538 @columns = map $_->{Val}, @row;
541 #warn $z++. ": $_\n" for @columns;
544 die "Unknown file type $type\n";
549 my @repeat = @columns[0..3];
551 foreach my $rate ( @rate ) {
556 foreach my $field ( @fields ) {
558 my $value = shift @columns;
560 if ( ref($field) eq 'CODE' ) {
561 #&{$field}(\%hash, $value);
562 push @later, $field, $value;
564 } elsif ($field) { #edit_import
565 #??? $hash{$field} = $value if length($value);
566 $hash{$field} = $value if defined($value) && length($value);
571 unshift @columns, @repeat; #edit_import put these back on for next time
573 my $class = "FS::$table";
575 my $record = $class->new( \%hash );
577 $record->ratenum($rate->ratenum); #edit_import
579 #edit_improt n/a my $param = {};
580 while ( scalar(@later) ) {
581 my $sub = shift @later;
582 my $data = shift @later;
583 #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
584 &{$sub}($record, $data); #edit_import - don't have $conf
585 #edit_import wrong loop last if exists( $param->{skiprow} );
587 #edit_import wrong loop next if exists( $param->{skiprow} );
589 #edit_import update or insert, not just insert
592 'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
597 $record->ratedetailnum($old->ratedetailnum);
598 $error = $record->replace($old)
604 $dbh->rollback if $oldAutoCommit;
605 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
613 if ( $job && time - $min_sec > $last ) { #progress bar
614 $job->update_statustext( int(100 * $imported / $count) );
620 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
622 return "Empty file!" unless $imported || $param->{empty_ok};
634 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
635 schema.html from the base documentation.