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