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