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