summaryrefslogtreecommitdiff
path: root/FS/FS/rate_detail.pm
blob: 89333540121f86ef53a222b9f3f72d3da79319f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
package FS::rate_detail;
use base qw(FS::Record);

use strict;
use vars qw( $DEBUG $me );
use Tie::IxHash;
use FS::Record qw( qsearch qsearchs dbh );
use FS::rate;
use FS::rate_region;
use FS::rate_time;

$DEBUG = 0;
$me = '[FS::rate_detail]';

=head1 NAME

FS::rate_detail - Object methods for rate_detail records

=head1 SYNOPSIS

  use FS::rate_detail;

  $record = new FS::rate_detail \%hash;
  $record = new FS::rate_detail { 'column' => 'value' };

  $error = $record->insert;

  $error = $new_record->replace($old_record);

  $error = $record->delete;

  $error = $record->check;

=head1 DESCRIPTION

An FS::rate_detail object represents an call plan rate.  FS::rate_detail
inherits from FS::Record.  The following fields are currently supported:

=over 4

=item ratedetailnum - primary key

=item ratenum - rate plan (see L<FS::rate>)

=item orig_regionnum - call origination region

=item dest_regionnum - call destination region

=item min_included - included minutes

=item min_charge - charge per minute

=item sec_granularity - granularity in seconds, i.e. 6 or 60; 0 for per-call

=item classnum - usage class (see L<FS::usage_class>) if any for this rate

=item ratetimenum - rating time period (see L<FS::rate_time) if any

=item cdrtypenum - CDR type (see L<FS::cdr_type>) if any for this rate

=item region_group - Group in region group for rate plan

=item upstream_mult_charge - the multiplier to apply to the upstream price. 
Defaults to zero, and should stay zero unless this rate is intended to include
a markup on pre-rated CDRs.

=item upstream_mult_cost - the multiplier to apply to the upstream price to
calculate the wholesale cost.

=back

=head1 METHODS

=over 4

=item new HASHREF

Creates a new call plan rate.  To add the call plan rate to the database, see
L<"insert">.

Note that this stores the hash reference, not a distinct copy of the hash it
points to.  You can ask the object for a copy with the I<hash> method.

=cut

# the new method can be inherited from FS::Record, if a table method is defined

sub table { 'rate_detail'; }

=item insert

Adds this record to the database.  If there is an error, returns the error,
otherwise returns false.

=cut

# the insert method can be inherited from FS::Record

=item delete

Delete this record from the database.

=cut

# the delete method can be inherited from FS::Record

=item replace OLD_RECORD

Replaces the OLD_RECORD with this one in the database.  If there is an error,
returns the error, otherwise returns false.

=cut

# the replace method can be inherited from FS::Record

=item check

Checks all fields to make sure this is a valid call plan rate.  If there is
an error, returns the error, otherwise returns false.  Called by the insert
and replace methods.

=cut

# the check method should currently be supplied - FS::Record contains some
# data checking routines

sub check {
  my $self = shift;

  my $error = 
       $self->ut_numbern('ratedetailnum')
    || $self->ut_foreign_key('ratenum', 'rate', 'ratenum')
    || $self->ut_foreign_keyn('orig_regionnum', 'rate_region', 'regionnum' )
    || $self->ut_foreign_keyn('dest_regionnum', 'rate_region', 'regionnum' )
    || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
    || $self->ut_number('min_included')

    #|| $self->ut_money('min_charge')
    #good enough for now...
    || $self->ut_floatn('conn_charge')
    || $self->ut_floatn('conn_cost')
    || $self->ut_float('min_charge')
    || $self->ut_floatn('min_cost')

    || $self->ut_number('sec_granularity')

    || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum' )
    || $self->ut_enum('region_group',    [ '', 'Y' ])

    || $self->ut_floatn('upstream_mult_charge')
    || $self->ut_floatn('upstream_mult_cost')
  ;
  return $error if $error;

  $self->SUPER::check;
}

=item rate 

Returns the parent call plan (see L<FS::rate>) associated with this call plan
rate.

=item orig_region 

Returns the origination region (see L<FS::rate_region>) associated with this
call plan rate.

=cut

sub orig_region {
  my $self = shift;
  qsearchs('rate_region', { 'regionnum' => $self->orig_regionnum } );
}

=item dest_region 

Returns the destination region (see L<FS::rate_region>) associated with this
call plan rate.

=cut

sub dest_region {
  my $self = shift;
  qsearchs('rate_region', { 'regionnum' => $self->dest_regionnum } );
}

=item dest_regionname

Returns the name of the destination region (see L<FS::rate_region>) associated
with this call plan rate.

=cut

sub dest_regionname {
  my $self = shift;
  my $dest_region = $self->dest_region;
  $dest_region ? $dest_region->regionname : 'Global default';
    # should be 'Anywhere' or something, to indicate that it's the
    # cross-region default
}

=item dest_prefixes_short

Returns a short list of the prefixes for the destination region
(see L<FS::rate_region>) associated with this call plan rate.

=cut

sub dest_prefixes_short {
  my $self = shift;
  my $dest_region = $self->dest_region;
  $dest_region ? $dest_region->prefixes_short : '';
}

=item rate_time

Returns the L<FS::rate_time> object associated with this call 
plan rate, if there is one.

=cut

sub rate_time {
  my $self = shift;
  $self->ratetimenum ? FS::rate_time->by_key($self->ratetimenum) : ();
}

=item rate_time_name

Returns the I<ratetimename> field of the L<FS::rate_time> object
associated with this rate plan.

=cut

sub rate_time_name {
  my $self = shift;
  $self->ratetimenum ? $self->rate_time->ratetimename : '(any time)';
}

=item classname

Returns the name of the usage class (see L<FS::usage_class>) associated with
this call plan rate.

=cut

sub classname {
  my $self = shift;
  my $usage_class = qsearchs('usage_class', { classnum => $self->classnum });
  $usage_class ? $usage_class->classname : '';
}

=item cdrtypename

Returns the name of the CDR type (see L<FS::cdr_type) associated with this 
rate, if there is one.  If not, returns the cdrtypenum itself.  This will 
only return an empty string if cdrtypenum is NULL.

=cut

sub cdrtypename {
  my $self = shift;
  my $cdrtypenum = $self->cdrtypenum or return '';
  my $cdr_type = qsearchs('cdr_type', { cdrtypenum => $cdrtypenum });
  return $cdr_type ? $cdr_type->cdrtypename : $cdrtypenum;
}

=back

=head1 SUBROUTINES

=over 4

=item granularities

  Returns an (ordered) hash of granularity => name pairs

=cut

tie my %granularities, 'Tie::IxHash',
  '1', => '1 second',
  '6'  => '6 second',
  '30' => '30 second', # '1/2 minute',
  '60' => 'minute',
  '0'  => 'call',
;

sub granularities {
  %granularities;
}

=item conn_secs

  Returns an (ordered) hash of conn_sec => name pairs

=cut

tie my %conn_secs, 'Tie::IxHash',
    '0' => 'connection',
    '1' => 'first second',
    '6' => 'first 6 seconds',
   '30' => 'first 30 seconds', # '1/2 minute',
   '60' => 'first minute',
  '120' => 'first 2 minutes',
  '180' => 'first 3 minutes',
  '300' => 'first 5 minutes',
;

sub conn_secs {
  %conn_secs;
}

=item process_edit_import

=cut

use Data::Dumper;
sub process_edit_import {
  my $job = shift;

  #do we actually belong in rate_detail, like 'table' says?  even though we
  # can possible create new rate records, that's a side effect, mostly we
  # do edit rate_detail records in batch...

  my $opt = { 'table'          => 'rate_detail',
              'params'         => [], #required, apparantly
              'formats'        => { 'default' => [
                'dest_regionnum',
                '', #regionname
                '', #country
                '', #prefixes
                #loop these
                'min_included',
                'min_charge',
                sub {
                  my( $rate_detail, $g ) = @_;
                  $g  = 0  if $g =~ /^\s*(per-)?call\s*$/i;
                  $g  = 60 if $g =~ /^\s*minute\s*$/i;
                  $g  =~ /^(\d+)/ or die "can't parse granularity: $g".
                                         " for record ". Dumper($rate_detail);
                  $rate_detail->sec_granularity($1);
                },
                'classnum',
              ] },
              'format_headers' => { 'default' => 1, },
              'format_types'   => { 'default' => 'xls' },
            };

  #false laziness w/
  #FS::Record::process_batch_import( $job, $opt, @_ );
  
  my $table = $opt->{table};
  my @pass_params = @{ $opt->{params} };
  my %formats = %{ $opt->{formats} };

  my $param = shift;
  warn Dumper($param) if $DEBUG;
  
  my $files = $param->{'uploaded_files'}
    or die "No files provided.\n";

  my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;

  my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
  my $file = $dir. $files{'file'};

  my $error =
    #false laziness w/
    #FS::Record::batch_import( {
    FS::rate_detail::edit_import( {
      #class-static
      table                      => $table,
      formats                    => \%formats,
      format_types               => $opt->{format_types},
      format_headers             => $opt->{format_headers},
      format_sep_chars           => $opt->{format_sep_chars},
      format_fixedlength_formats => $opt->{format_fixedlength_formats},
      #per-import
      job                        => $job,
      file                       => $file,
      #type                       => $type,
      format                     => $param->{format},
      params                     => { map { $_ => $param->{$_} } @pass_params },
      #?
      default_csv                => $opt->{default_csv},
    } );

  unlink $file;

  die "$error\n" if $error;

}

=item edit_import

=cut

#false laziness w/ #FS::Record::batch_import, grep "edit_import" for differences
#could be turned into callbacks or something
use Text::CSV_XS;
sub edit_import {
  my $param = shift;

  warn "$me edit_import call with params: \n". Dumper($param)
    if $DEBUG;

  my $table   = $param->{table};
  my $formats = $param->{formats};

  my $job     = $param->{job};
  my $file    = $param->{file};
  my $format  = $param->{'format'};
  my $params  = $param->{params} || {};

  die "unknown format $format" unless exists $formats->{ $format };

  my $type = $param->{'format_types'}
             ? $param->{'format_types'}{ $format }
             : $param->{type} || 'csv';

  unless ( $type ) {
    if ( $file =~ /\.(\w+)$/i ) {
      $type = lc($1);
    } else {
      #or error out???
      warn "can't parse file type from filename $file; defaulting to CSV";
      $type = 'csv';
    }
    $type = 'csv'
      if $param->{'default_csv'} && $type ne 'xls';
  }

  my $header = $param->{'format_headers'}
                 ? $param->{'format_headers'}{ $param->{'format'} }
                 : 0;

  my $sep_char = $param->{'format_sep_chars'}
                   ? $param->{'format_sep_chars'}{ $param->{'format'} }
                   : ',';

  my $fixedlength_format =
    $param->{'format_fixedlength_formats'}
      ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
      : '';

  my @fields = @{ $formats->{ $format } };

  my $row = 0;
  my $count;
  my $parser;
  my @buffer = ();
  my @header = (); #edit_import
  if ( $type eq 'csv' || $type eq 'fixedlength' ) {

    if ( $type eq 'csv' ) {

      my %attr = ();
      $attr{sep_char} = $sep_char if $sep_char;
      $parser = new Text::CSV_XS \%attr;

    } elsif ( $type eq 'fixedlength' ) {

      eval "use Parse::FixedLength;";
      die $@ if $@;
      $parser = new Parse::FixedLength $fixedlength_format;
 
    } else {
      die "Unknown file type $type\n";
    }

    @buffer = split(/\r?\n/, slurp($file) );
    splice(@buffer, 0, ($header || 0) );
    $count = scalar(@buffer);

  } elsif ( $type eq 'xls' ) {

    eval "use Spreadsheet::ParseExcel;";
    die $@ if $@;

    eval "use DateTime::Format::Excel;";
    #for now, just let the error be thrown if it is used, since only CDR
    # formats bill_west and troop use it, not other excel-parsing things
    #die $@ if $@;

    my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);

    $parser = $excel->{Worksheet}[0]; #first sheet

    $count = $parser->{MaxRow} || $parser->{MinRow};
    $count++;

    $row = $header || 0;

    #edit_import - need some magic to parse the header
    if ( $header ) {
      my @header_row = @{ $parser->{Cells}[$0] };
      @header = map $_->{Val}, @header_row;
    }

  } else {
    die "Unknown file type $type\n";
  }

  #my $columns;

  local $SIG{HUP} = 'IGNORE';
  local $SIG{INT} = 'IGNORE';
  local $SIG{QUIT} = 'IGNORE';
  local $SIG{TERM} = 'IGNORE';
  local $SIG{TSTP} = 'IGNORE';
  local $SIG{PIPE} = 'IGNORE';

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;
  my $dbh = dbh;

  #edit_import - use the header to setup looping over different rates
  my @rate = ();
  if ( @header ) {
    splice(@header,0,4); # # Region Country Prefixes
    while ( my @next = splice(@header,0,4) ) {
      my $rate;
      if ( $next[0] =~ /^(\d+):\s*([^:]+):/ ) {
        $rate = qsearchs('rate', { 'ratenum' => $1 } )
          or die "unknown ratenum $1";
      } elsif ( $next[0] =~ /^(NEW:)?\s*([^:]+)/i ) {
        $rate = new FS::rate { 'ratename' => $2 };
        my $error = $rate->insert;
        if ( $error ) {
          $dbh->rollback if $oldAutoCommit;
          return "error inserting new rate: $error\n";
        }
      }
      push @rate, $rate;
    }
  }
  die unless @rate;
  
  my $line;
  my $imported = 0;
  my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
  while (1) {

    my @columns = ();
    if ( $type eq 'csv' ) {

      last unless scalar(@buffer);
      $line = shift(@buffer);

      $parser->parse($line) or do {
        $dbh->rollback if $oldAutoCommit;
        return "can't parse: ". $parser->error_input();
      };
      @columns = $parser->fields();

    } elsif ( $type eq 'fixedlength' ) {

      @columns = $parser->parse($line);

    } elsif ( $type eq 'xls' ) {

      last if $row > ($parser->{MaxRow} || $parser->{MinRow})
           || ! $parser->{Cells}[$row];

      my @row = @{ $parser->{Cells}[$row] };
      @columns = map $_->{Val}, @row;

      #my $z = 'A';
      #warn $z++. ": $_\n" for @columns;

    } else {
      die "Unknown file type $type\n";
    }

    #edit_import loop

    my @repeat = @columns[0..3];

    foreach my $rate ( @rate ) {

      my @later = ();
      my %hash = %$params;

      foreach my $field ( @fields ) {

        my $value = shift @columns;
       
        if ( ref($field) eq 'CODE' ) {
          #&{$field}(\%hash, $value);
          push @later, $field, $value;
        #} else {
        } elsif ($field) { #edit_import
          #??? $hash{$field} = $value if length($value);
          $hash{$field} = $value if defined($value) && length($value);
        }

      }

      unshift @columns, @repeat; #edit_import put these back on for next time

      my $class = "FS::$table";

      my $record = $class->new( \%hash );

      $record->ratenum($rate->ratenum); #edit_import

      #edit_improt n/a my $param = {};
      while ( scalar(@later) ) {
        my $sub = shift @later;
        my $data = shift @later;
        #&{$sub}($record, $data, $conf, $param);# $record->&{$sub}($data, $conf);
        &{$sub}($record, $data); #edit_import - don't have $conf
        #edit_import wrong loop last if exists( $param->{skiprow} );
      }
      #edit_import wrong loop next if exists( $param->{skiprow} );

      #edit_import update or insert, not just insert
      my $old = qsearchs({
        'table'   => $table,
        'hashref' => { map { $_ => $record->$_() } qw(ratenum dest_regionnum) },
      });

      my $error;
      if ( $old ) {
        $record->ratedetailnum($old->ratedetailnum);
        $error = $record->replace($old)
      } else {
        $record->insert;
      }

      if ( $error ) {
        $dbh->rollback if $oldAutoCommit;
        return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
      }

    }

    $row++;
    $imported++;

    if ( $job && time - $min_sec > $last ) { #progress bar
      $job->update_statustext( int(100 * $imported / $count) );
      $last = time;
    }

  }

  $dbh->commit or die $dbh->errstr if $oldAutoCommit;;

  return "Empty file!" unless $imported || $param->{empty_ok};

  ''; #no error

}

=back

=head1 BUGS

=head1 SEE ALSO

L<FS::rate>, L<FS::rate_region>, L<FS::Record>,
schema.html from the base documentation.

=cut

1;