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