communigate provisioning phase 2: Domain:Account Defaults:Settings: RulesAllowed...
[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 =item conn_secs
236
237   Returns an (ordered) hash of conn_sec => name pairs
238
239 =cut
240
241 tie my %conn_secs, 'Tie::IxHash',
242     '0' => 'connection',
243     '1' => 'first second',
244     '6' => 'first 6 seconds',
245    '30' => 'first 30 seconds', # '1/2 minute',
246    '60' => 'first minute',
247   '120' => 'first 2 minutes',
248   '180' => 'first 3 minutes',
249   '300' => 'first 5 minutes',
250 ;
251
252 sub conn_secs {
253   %conn_secs;
254 }
255
256 =item process_edit_import
257
258 =cut
259
260 use Storable qw(thaw);
261 use Data::Dumper;
262 use MIME::Base64;
263 sub process_edit_import {
264   my $job = shift;
265
266   #do we actually belong in rate_detail, like 'table' says?  even though we
267   # can possible create new rate records, that's a side effect, mostly we
268   # do edit rate_detail records in batch...
269
270   my $opt = { 'table'          => 'rate_detail',
271               'params'         => [], #required, apparantly
272               'formats'        => { 'default' => [
273                 'dest_regionnum',
274                 '', #regionname
275                 '', #country
276                 '', #prefixes
277                 #loop these
278                 'min_included',
279                 'min_charge',
280                 sub {
281                   my( $rate_detail, $g ) = @_;
282                   $g  = 0  if $g =~ /^\s*(per-)?call\s*$/i;
283                   $g  = 60 if $g =~ /^\s*minute\s*$/i;
284                   $g  =~ /^(\d+)/ or die "can't parse granularity: $g".
285                                          " for record ". Dumper($rate_detail);
286                   $rate_detail->sec_granularity($1);
287                 },
288                 'classnum',
289               ] },
290               'format_headers' => { 'default' => 1, },
291               'format_types'   => { 'default' => 'xls' },
292             };
293
294   #false laziness w/
295   #FS::Record::process_batch_import( $job, $opt, @_ );
296   
297   my $table = $opt->{table};
298   my @pass_params = @{ $opt->{params} };
299   my %formats = %{ $opt->{formats} };
300
301   my $param = thaw(decode_base64(shift));
302   warn Dumper($param) if $DEBUG;
303   
304   my $files = $param->{'uploaded_files'}
305     or die "No files provided.\n";
306
307   my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
308
309   my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
310   my $file = $dir. $files{'file'};
311
312   my $error =
313     #false laziness w/
314     #FS::Record::batch_import( {
315     FS::rate_detail::edit_import( {
316       #class-static
317       table                      => $table,
318       formats                    => \%formats,
319       format_types               => $opt->{format_types},
320       format_headers             => $opt->{format_headers},
321       format_sep_chars           => $opt->{format_sep_chars},
322       format_fixedlength_formats => $opt->{format_fixedlength_formats},
323       #per-import
324       job                        => $job,
325       file                       => $file,
326       #type                       => $type,
327       format                     => $param->{format},
328       params                     => { map { $_ => $param->{$_} } @pass_params },
329       #?
330       default_csv                => $opt->{default_csv},
331     } );
332
333   unlink $file;
334
335   die "$error\n" if $error;
336
337 }
338
339 =item edit_import
340
341 =cut
342
343 #false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
344 #could be turned into callbacks or something
345 use Text::CSV_XS;
346 sub edit_import {
347   my $param = shift;
348
349   warn "$me edit_import call with params: \n". Dumper($param)
350     if $DEBUG;
351
352   my $table   = $param->{table};
353   my $formats = $param->{formats};
354
355   my $job     = $param->{job};
356   my $file    = $param->{file};
357   my $format  = $param->{'format'};
358   my $params  = $param->{params} || {};
359
360   die "unknown format $format" unless exists $formats->{ $format };
361
362   my $type = $param->{'format_types'}
363              ? $param->{'format_types'}{ $format }
364              : $param->{type} || 'csv';
365
366   unless ( $type ) {
367     if ( $file =~ /\.(\w+)$/i ) {
368       $type = lc($1);
369     } else {
370       #or error out???
371       warn "can't parse file type from filename $file; defaulting to CSV";
372       $type = 'csv';
373     }
374     $type = 'csv'
375       if $param->{'default_csv'} && $type ne 'xls';
376   }
377
378   my $header = $param->{'format_headers'}
379                  ? $param->{'format_headers'}{ $param->{'format'} }
380                  : 0;
381
382   my $sep_char = $param->{'format_sep_chars'}
383                    ? $param->{'format_sep_chars'}{ $param->{'format'} }
384                    : ',';
385
386   my $fixedlength_format =
387     $param->{'format_fixedlength_formats'}
388       ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
389       : '';
390
391   my @fields = @{ $formats->{ $format } };
392
393   my $row = 0;
394   my $count;
395   my $parser;
396   my @buffer = ();
397   my @header = (); #edit_import
398   if ( $type eq 'csv' || $type eq 'fixedlength' ) {
399
400     if ( $type eq 'csv' ) {
401
402       my %attr = ();
403       $attr{sep_char} = $sep_char if $sep_char;
404       $parser = new Text::CSV_XS \%attr;
405
406     } elsif ( $type eq 'fixedlength' ) {
407
408       eval "use Parse::FixedLength;";
409       die $@ if $@;
410       $parser = new Parse::FixedLength $fixedlength_format;
411  
412     } else {
413       die "Unknown file type $type\n";
414     }
415
416     @buffer = split(/\r?\n/, slurp($file) );
417     splice(@buffer, 0, ($header || 0) );
418     $count = scalar(@buffer);
419
420   } elsif ( $type eq 'xls' ) {
421
422     eval "use Spreadsheet::ParseExcel;";
423     die $@ if $@;
424
425     eval "use DateTime::Format::Excel;";
426     #for now, just let the error be thrown if it is used, since only CDR
427     # formats bill_west and troop use it, not other excel-parsing things
428     #die $@ if $@;
429
430     my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
431
432     $parser = $excel->{Worksheet}[0]; #first sheet
433
434     $count = $parser->{MaxRow} || $parser->{MinRow};
435     $count++;
436
437     $row = $header || 0;
438
439     #edit_import - need some magic to parse the header
440     if ( $header ) {
441       my @header_row = @{ $parser->{Cells}[$0] };
442       @header = map $_->{Val}, @header_row;
443     }
444
445   } else {
446     die "Unknown file type $type\n";
447   }
448
449   #my $columns;
450
451   local $SIG{HUP} = 'IGNORE';
452   local $SIG{INT} = 'IGNORE';
453   local $SIG{QUIT} = 'IGNORE';
454   local $SIG{TERM} = 'IGNORE';
455   local $SIG{TSTP} = 'IGNORE';
456   local $SIG{PIPE} = 'IGNORE';
457
458   my $oldAutoCommit = $FS::UID::AutoCommit;
459   local $FS::UID::AutoCommit = 0;
460   my $dbh = dbh;
461
462   #edit_import - use the header to setup looping over different rates
463   my @rate = ();
464   if ( @header ) {
465     splice(@header,0,4); # # Region Country Prefixes
466     while ( my @next = splice(@header,0,4) ) {
467       my $rate;
468       if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
469         $rate = qsearchs('rate', { 'ratenum' => $1 } )
470           or die "unknown ratenum $1";
471       } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
472         $rate = new FS::rate { 'ratename' => $2 };
473         my $error = $rate->insert;
474         if ( $error ) {
475           $dbh->rollback if $oldAutoCommit;
476           return "error inserting new rate: $error\n";
477         }
478       }
479       push @rate, $rate;
480     }
481   }
482   die unless @rate;
483   
484   my $line;
485   my $imported = 0;
486   my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
487   while (1) {
488
489     my @columns = ();
490     if ( $type eq 'csv' ) {
491
492       last unless scalar(@buffer);
493       $line = shift(@buffer);
494
495       $parser->parse($line) or do {
496         $dbh->rollback if $oldAutoCommit;
497         return "can't parse: ". $parser->error_input();
498       };
499       @columns = $parser->fields();
500
501     } elsif ( $type eq 'fixedlength' ) {
502
503       @columns = $parser->parse($line);
504
505     } elsif ( $type eq 'xls' ) {
506
507       last if $row > ($parser->{MaxRow} || $parser->{MinRow})
508            || ! $parser->{Cells}[$row];
509
510       my @row = @{ $parser->{Cells}[$row] };
511       @columns = map $_->{Val}, @row;
512
513       #my $z = 'A';
514       #warn $z++. ": $_\n" for @columns;
515
516     } else {
517       die "Unknown file type $type\n";
518     }
519
520     #edit_import loop
521
522     my @repeat = @columns[0..3];
523
524     foreach my $rate ( @rate ) {
525
526       my @later = ();
527       my %hash = %$params;
528
529       foreach my $field ( @fields ) {
530
531         my $value = shift @columns;
532        
533         if ( ref($field) eq 'CODE' ) {
534           #&{$field}(\%hash, $value);
535           push @later, $field, $value;
536         #} else {
537         } elsif ($field) { #edit_import
538           #??? $hash{$field} = $value if length($value);
539           $hash{$field} = $value if defined($value) && length($value);
540         }
541
542       }
543
544       unshift @columns, @repeat; #edit_import put these back on for next time
545
546       my $class = "FS::$table";
547
548       my $record = $class->new( \%hash );
549
550       $record->ratenum($rate->ratenum); #edit_import
551
552       #edit_improt n/a my $param = {};
553       while ( scalar(@later) ) {
554         my $sub = shift @later;
555         my $data = shift @later;
556         #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
557         &{$sub}($record, $data); #edit_import - don't have $conf
558         #edit_import wrong loop last if exists( $param->{skiprow} );
559       }
560       #edit_import wrong loop next if exists( $param->{skiprow} );
561
562       #edit_import update or insert, not just insert
563       my $old = qsearchs({
564         'table'   => $table,
565         'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
566       });
567
568       my $error;
569       if ( $old ) {
570         $record->ratedetailnum($old->ratedetailnum);
571         $error = $record->replace($old)
572       } else {
573         $record->insert;
574       }
575
576       if ( $error ) {
577         $dbh->rollback if $oldAutoCommit;
578         return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
579       }
580
581     }
582
583     $row++;
584     $imported++;
585
586     if ( $job && time - $min_sec > $last ) { #progress bar
587       $job->update_statustext( int(100 * $imported / $count) );
588       $last = time;
589     }
590
591   }
592
593   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
594
595   return "Empty file!" unless $imported || $param->{empty_ok};
596
597   ''; #no error
598
599 }
600
601 =back
602
603 =head1 BUGS
604
605 =head1 SEE ALSO
606
607 L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
608 schema.html from the base documentation.
609
610 =cut
611
612 1;
613