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