allow a default rate detail for each CDR type, #38633
[freeside.git] / FS / FS / rate_detail.pm
1 package FS::rate_detail;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $me );
5 use FS::Record qw( qsearch qsearchs dbh );
6 use FS::rate;
7 use FS::rate_region;
8 use FS::rate_time;
9 use Tie::IxHash;
10
11 @ISA = qw(FS::Record);
12
13 $DEBUG = 0;
14 $me = '[FS::rate_detail]';
15
16 =head1 NAME
17
18 FS::rate_detail - Object methods for rate_detail records
19
20 =head1 SYNOPSIS
21
22   use FS::rate_detail;
23
24   $record = new FS::rate_detail \%hash;
25   $record = new FS::rate_detail { 'column' => 'value' };
26
27   $error = $record->insert;
28
29   $error = $new_record->replace($old_record);
30
31   $error = $record->delete;
32
33   $error = $record->check;
34
35 =head1 DESCRIPTION
36
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:
39
40 =over 4
41
42 =item ratedetailnum - primary key
43
44 =item ratenum - rate plan (see L<FS::rate>)
45
46 =item orig_regionnum - call origination region
47
48 =item dest_regionnum - call destination region
49
50 =item min_included - included minutes
51
52 =item min_charge - charge per minute
53
54 =item sec_granularity - granularity in seconds, i.e. 6 or 60; 0 for per-call
55
56 =item classnum - usage class (see L<FS::usage_class>) if any for this rate
57
58 =item ratetimenum - rating time period (see L<FS::rate_time) if any
59
60 =item cdrtypenum - CDR type (see L<FS::cdr_type>) if any for this rate
61
62 =item region_group - Group in region group for rate plan
63
64 =item upstream_mult_charge - the multiplier to apply to the upstream price. 
65 Defaults to zero, and should stay zero unless this rate is intended to include
66 a markup on pre-rated CDRs.
67
68 =item upstream_mult_cost - the multiplier to apply to the upstream price to
69 calculate the wholesale cost.
70
71 =back
72
73 =head1 METHODS
74
75 =over 4
76
77 =item new HASHREF
78
79 Creates a new call plan rate.  To add the call plan rate to the database, see
80 L<"insert">.
81
82 Note that this stores the hash reference, not a distinct copy of the hash it
83 points to.  You can ask the object for a copy with the I<hash> method.
84
85 =cut
86
87 # the new method can be inherited from FS::Record, if a table method is defined
88
89 sub table { 'rate_detail'; }
90
91 =item insert
92
93 Adds this record to the database.  If there is an error, returns the error,
94 otherwise returns false.
95
96 =cut
97
98 # the insert method can be inherited from FS::Record
99
100 =item delete
101
102 Delete this record from the database.
103
104 =cut
105
106 # the delete method can be inherited from FS::Record
107
108 =item replace OLD_RECORD
109
110 Replaces the OLD_RECORD with this one in the database.  If there is an error,
111 returns the error, otherwise returns false.
112
113 =cut
114
115 # the replace method can be inherited from FS::Record
116
117 =item check
118
119 Checks all fields to make sure this is a valid call plan rate.  If there is
120 an error, returns the error, otherwise returns false.  Called by the insert
121 and replace methods.
122
123 =cut
124
125 # the check method should currently be supplied - FS::Record contains some
126 # data checking routines
127
128 sub check {
129   my $self = shift;
130
131   my $error = 
132        $self->ut_numbern('ratedetailnum')
133     || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
134     || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
135     || $self->ut_foreign_keyn('dest_regionnum', 'rate_region', 'regionnum' )
136     || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
137     || $self->ut_number('min_included')
138
139     #|| $self->ut_money('min_charge')
140     #good enough for now...
141     || $self->ut_floatn('conn_charge')
142     || $self->ut_floatn('conn_cost')
143     || $self->ut_float('min_charge')
144     || $self->ut_floatn('min_cost')
145
146     || $self->ut_number('sec_granularity')
147
148     || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
149     || $self->ut_enum('region_group',    [ '', 'Y' ])
150
151     || $self->ut_floatn('upstream_mult_charge')
152     || $self->ut_floatn('upstream_mult_cost')
153   ;
154   return $error if $error;
155
156   $self->SUPER::check;
157 }
158
159 =item rate 
160
161 Returns the parent call plan (see L<FS::rate>) associated with this call plan
162 rate.
163
164 =cut
165
166 sub rate {
167   my $self = shift;
168   qsearchs('rate', { 'ratenum' => $self->ratenum } );
169 }
170
171 =item orig_region 
172
173 Returns the origination region (see L<FS::rate_region>) associated with this
174 call plan rate.
175
176 =cut
177
178 sub orig_region {
179   my $self = shift;
180   qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
181 }
182
183 =item dest_region 
184
185 Returns the destination region (see L<FS::rate_region>) associated with this
186 call plan rate.
187
188 =cut
189
190 sub dest_region {
191   my $self = shift;
192   qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
193 }
194
195 =item dest_regionname
196
197 Returns the name of the destination region (see L<FS::rate_region>) associated
198 with this call plan rate.
199
200 =cut
201
202 sub dest_regionname {
203   my $self = shift;
204   my $dest_region = $self->dest_region;
205   $dest_region ? $dest_region->regionname : 'Global default';
206     # should be 'Anywhere' or something, to indicate that it's the
207     # cross-region default
208 }
209
210 =item dest_prefixes_short
211
212 Returns a short list of the prefixes for the destination region
213 (see L<FS::rate_region>) associated with this call plan rate.
214
215 =cut
216
217 sub dest_prefixes_short {
218   my $self = shift;
219   my $dest_region = $self->dest_region;
220   $dest_region ? $dest_region->prefixes_short : '';
221 }
222
223 =item rate_time
224
225 Returns the L<FS::rate_time> object associated with this call 
226 plan rate, if there is one.
227
228 =cut
229
230 sub rate_time {
231   my $self = shift;
232   $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
233 }
234
235 =item rate_time_name
236
237 Returns the I<ratetimename> field of the L<FS::rate_time> object
238 associated with this rate plan.
239
240 =cut
241
242 sub rate_time_name {
243   my $self = shift;
244   $self->ratetimenum ? $self->rate_time->ratetimename : '(any time)';
245 }
246
247 =item classname
248
249 Returns the name of the usage class (see L<FS::usage_class>) associated with
250 this call plan rate.
251
252 =cut
253
254 sub classname {
255   my $self = shift;
256   my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
257   $usage_class ? $usage_class->classname : '';
258 }
259
260 =item cdrtypename
261
262 Returns the name of the CDR type (see L<FS::cdr_type) associated with this 
263 rate, if there is one.  If not, returns the cdrtypenum itself.  This will 
264 only return an empty string if cdrtypenum is NULL.
265
266 =cut
267
268 sub cdrtypename {
269   my $self = shift;
270   my $cdrtypenum = $self->cdrtypenum or return '';
271   my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
272   return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
273 }
274
275 =back
276
277 =head1 SUBROUTINES
278
279 =over 4
280
281 =item granularities
282
283   Returns an (ordered) hash of granularity => name pairs
284
285 =cut
286
287 tie my %granularities, 'Tie::IxHash',
288   '1', => '1 second',
289   '6'  => '6 second',
290   '30' => '30 second', # '1/2 minute',
291   '60' => 'minute',
292   '0'  => 'call',
293 ;
294
295 sub granularities {
296   %granularities;
297 }
298
299 =item conn_secs
300
301   Returns an (ordered) hash of conn_sec => name pairs
302
303 =cut
304
305 tie my %conn_secs, 'Tie::IxHash',
306     '0' => 'connection',
307     '1' => 'first second',
308     '6' => 'first 6 seconds',
309    '30' => 'first 30 seconds', # '1/2 minute',
310    '60' => 'first minute',
311   '120' => 'first 2 minutes',
312   '180' => 'first 3 minutes',
313   '300' => 'first 5 minutes',
314 ;
315
316 sub conn_secs {
317   %conn_secs;
318 }
319
320 =item process_edit_import
321
322 =cut
323
324 use Storable qw(thaw);
325 use Data::Dumper;
326 use MIME::Base64;
327 sub process_edit_import {
328   my $job = shift;
329
330   #do we actually belong in rate_detail, like 'table' says?  even though we
331   # can possible create new rate records, that's a side effect, mostly we
332   # do edit rate_detail records in batch...
333
334   my $opt = { 'table'          => 'rate_detail',
335               'params'         => [], #required, apparantly
336               'formats'        => { 'default' => [
337                 'dest_regionnum',
338                 '', #regionname
339                 '', #country
340                 '', #prefixes
341                 #loop these
342                 'min_included',
343                 'min_charge',
344                 sub {
345                   my( $rate_detail, $g ) = @_;
346                   $g  = 0  if $g =~ /^\s*(per-)?call\s*$/i;
347                   $g  = 60 if $g =~ /^\s*minute\s*$/i;
348                   $g  =~ /^(\d+)/ or die "can't parse granularity: $g".
349                                          " for record ". Dumper($rate_detail);
350                   $rate_detail->sec_granularity($1);
351                 },
352                 'classnum',
353               ] },
354               'format_headers' => { 'default' => 1, },
355               'format_types'   => { 'default' => 'xls' },
356             };
357
358   #false laziness w/
359   #FS::Record::process_batch_import( $job, $opt, @_ );
360   
361   my $table = $opt->{table};
362   my @pass_params = @{ $opt->{params} };
363   my %formats = %{ $opt->{formats} };
364
365   my $param = thaw(decode_base64(shift));
366   warn Dumper($param) if $DEBUG;
367   
368   my $files = $param->{'uploaded_files'}
369     or die "No files provided.\n";
370
371   my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
372
373   my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
374   my $file = $dir. $files{'file'};
375
376   my $error =
377     #false laziness w/
378     #FS::Record::batch_import( {
379     FS::rate_detail::edit_import( {
380       #class-static
381       table                      => $table,
382       formats                    => \%formats,
383       format_types               => $opt->{format_types},
384       format_headers             => $opt->{format_headers},
385       format_sep_chars           => $opt->{format_sep_chars},
386       format_fixedlength_formats => $opt->{format_fixedlength_formats},
387       #per-import
388       job                        => $job,
389       file                       => $file,
390       #type                       => $type,
391       format                     => $param->{format},
392       params                     => { map { $_ => $param->{$_} } @pass_params },
393       #?
394       default_csv                => $opt->{default_csv},
395     } );
396
397   unlink $file;
398
399   die "$error\n" if $error;
400
401 }
402
403 =item edit_import
404
405 =cut
406
407 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
408 #could be turned into callbacks or something
409 use Text::CSV_XS;
410 sub edit_import {
411   my $param = shift;
412
413   warn "$me edit_import call with params: \n". Dumper($param)
414     if $DEBUG;
415
416   my $table   = $param->{table};
417   my $formats = $param->{formats};
418
419   my $job     = $param->{job};
420   my $file    = $param->{file};
421   my $format  = $param->{'format'};
422   my $params  = $param->{params} || {};
423
424   die "unknown format $format" unless exists $formats->{ $format };
425
426   my $type = $param->{'format_types'}
427              ? $param->{'format_types'}{ $format }
428              : $param->{type} || 'csv';
429
430   unless ( $type ) {
431     if ( $file =~ /\.(\w+)$/i ) {
432       $type = lc($1);
433     } else {
434       #or error out???
435       warn "can't parse file type from filename $file; defaulting to CSV";
436       $type = 'csv';
437     }
438     $type = 'csv'
439       if $param->{'default_csv'} && $type ne 'xls';
440   }
441
442   my $header = $param->{'format_headers'}
443                  ? $param->{'format_headers'}{ $param->{'format'} }
444                  : 0;
445
446   my $sep_char = $param->{'format_sep_chars'}
447                    ? $param->{'format_sep_chars'}{ $param->{'format'} }
448                    : ',';
449
450   my $fixedlength_format =
451     $param->{'format_fixedlength_formats'}
452       ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
453       : '';
454
455   my @fields = @{ $formats->{ $format } };
456
457   my $row = 0;
458   my $count;
459   my $parser;
460   my @buffer = ();
461   my @header = (); #edit_import
462   if ( $type eq 'csv' || $type eq 'fixedlength' ) {
463
464     if ( $type eq 'csv' ) {
465
466       my %attr = ();
467       $attr{sep_char} = $sep_char if $sep_char;
468       $parser = new Text::CSV_XS \%attr;
469
470     } elsif ( $type eq 'fixedlength' ) {
471
472       eval "use Parse::FixedLength;";
473       die $@ if $@;
474       $parser = new Parse::FixedLength $fixedlength_format;
475  
476     } else {
477       die "Unknown file type $type\n";
478     }
479
480     @buffer = split(/\r?\n/, slurp($file) );
481     splice(@buffer, 0, ($header || 0) );
482     $count = scalar(@buffer);
483
484   } elsif ( $type eq 'xls' ) {
485
486     eval "use Spreadsheet::ParseExcel;";
487     die $@ if $@;
488
489     eval "use DateTime::Format::Excel;";
490     #for now, just let the error be thrown if it is used, since only CDR
491     # formats bill_west and troop use it, not other excel-parsing things
492     #die $@ if $@;
493
494     my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
495
496     $parser = $excel->{Worksheet}[0]; #first sheet
497
498     $count = $parser->{MaxRow} || $parser->{MinRow};
499     $count++;
500
501     $row = $header || 0;
502
503     #edit_import - need some magic to parse the header
504     if ( $header ) {
505       my @header_row = @{ $parser->{Cells}[$0] };
506       @header = map $_->{Val}, @header_row;
507     }
508
509   } else {
510     die "Unknown file type $type\n";
511   }
512
513   #my $columns;
514
515   local $SIG{HUP} = 'IGNORE';
516   local $SIG{INT} = 'IGNORE';
517   local $SIG{QUIT} = 'IGNORE';
518   local $SIG{TERM} = 'IGNORE';
519   local $SIG{TSTP} = 'IGNORE';
520   local $SIG{PIPE} = 'IGNORE';
521
522   my $oldAutoCommit = $FS::UID::AutoCommit;
523   local $FS::UID::AutoCommit = 0;
524   my $dbh = dbh;
525
526   #edit_import - use the header to setup looping over different rates
527   my @rate = ();
528   if ( @header ) {
529     splice(@header,0,4); # # Region Country Prefixes
530     while ( my @next = splice(@header,0,4) ) {
531       my $rate;
532       if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
533         $rate = qsearchs('rate', { 'ratenum' => $1 } )
534           or die "unknown ratenum $1";
535       } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
536         $rate = new FS::rate { 'ratename' => $2 };
537         my $error = $rate->insert;
538         if ( $error ) {
539           $dbh->rollback if $oldAutoCommit;
540           return "error inserting new rate: $error\n";
541         }
542       }
543       push @rate, $rate;
544     }
545   }
546   die unless @rate;
547   
548   my $line;
549   my $imported = 0;
550   my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
551   while (1) {
552
553     my @columns = ();
554     if ( $type eq 'csv' ) {
555
556       last unless scalar(@buffer);
557       $line = shift(@buffer);
558
559       $parser->parse($line) or do {
560         $dbh->rollback if $oldAutoCommit;
561         return "can't parse: ". $parser->error_input();
562       };
563       @columns = $parser->fields();
564
565     } elsif ( $type eq 'fixedlength' ) {
566
567       @columns = $parser->parse($line);
568
569     } elsif ( $type eq 'xls' ) {
570
571       last if $row > ($parser->{MaxRow} || $parser->{MinRow})
572            || ! $parser->{Cells}[$row];
573
574       my @row = @{ $parser->{Cells}[$row] };
575       @columns = map $_->{Val}, @row;
576
577       #my $z = 'A';
578       #warn $z++. ": $_\n" for @columns;
579
580     } else {
581       die "Unknown file type $type\n";
582     }
583
584     #edit_import loop
585
586     my @repeat = @columns[0..3];
587
588     foreach my $rate ( @rate ) {
589
590       my @later = ();
591       my %hash = %$params;
592
593       foreach my $field ( @fields ) {
594
595         my $value = shift @columns;
596        
597         if ( ref($field) eq 'CODE' ) {
598           #&{$field}(\%hash, $value);
599           push @later, $field, $value;
600         #} else {
601         } elsif ($field) { #edit_import
602           #??? $hash{$field} = $value if length($value);
603           $hash{$field} = $value if defined($value) && length($value);
604         }
605
606       }
607
608       unshift @columns, @repeat; #edit_import put these back on for next time
609
610       my $class = "FS::$table";
611
612       my $record = $class->new( \%hash );
613
614       $record->ratenum($rate->ratenum); #edit_import
615
616       #edit_improt n/a my $param = {};
617       while ( scalar(@later) ) {
618         my $sub = shift @later;
619         my $data = shift @later;
620         #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
621         &{$sub}($record, $data); #edit_import - don't have $conf
622         #edit_import wrong loop last if exists( $param->{skiprow} );
623       }
624       #edit_import wrong loop next if exists( $param->{skiprow} );
625
626       #edit_import update or insert, not just insert
627       my $old = qsearchs({
628         'table'   => $table,
629         'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
630       });
631
632       my $error;
633       if ( $old ) {
634         $record->ratedetailnum($old->ratedetailnum);
635         $error = $record->replace($old)
636       } else {
637         $record->insert;
638       }
639
640       if ( $error ) {
641         $dbh->rollback if $oldAutoCommit;
642         return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
643       }
644
645     }
646
647     $row++;
648     $imported++;
649
650     if ( $job && time - $min_sec > $last ) { #progress bar
651       $job->update_statustext( int(100 * $imported / $count) );
652       $last = time;
653     }
654
655   }
656
657   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
658
659   return "Empty file!" unless $imported || $param->{empty_ok};
660
661   ''; #no error
662
663 }
664
665 =back
666
667 =head1 BUGS
668
669 =head1 SEE ALSO
670
671 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
672 schema.html from the base documentation.
673
674 =cut
675
676 1;
677