summaryrefslogtreecommitdiff
path: root/bin/cdr.reimport
blob: 23060387d7d0491ba88d1bc7d96e4f18148471e9 (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
#!/usr/bin/perl
#
# Usage:
#  cdr.reimport user format filename
#

use strict;
use FS::UID qw(adminsuidsetup);
use FS::Record qw(qsearch);
use FS::cdr;

my $user = shift or die &usage;
adminsuidsetup $user;

my $format = shift or die &usage;

my $file = shift;

my($new, $rep, $skip) = (0, 0, 0);

#this is what makes it a reimport and should probably be moved to cdr.pm
my $cb = sub {
  my($cdr, $param) = @_;

  my @exists = qsearch('cdr', {
    map { $_ => $cdr->$_() }
      qw( uniqueid startdate enddate src dst charged_party )
  });

  unless ( scalar(@exists) ) {
    $new++;
    return;
  }

  if ( scalar(@exists) == 2 ) {
    if ( $exists[0]->freesidestatus || $exists[1]->freesidestatus ) {
      return "processed double record for uniqueid ". $cdr->uniqueid. "\n";
    }
    warn "deleting double record for uniqueid ". $cdr->uniqueid. "\n";
    my $extra = shift @exists;
    my $error = $extra->delete;
    return $error if $error;
  }

  return "too many matches (". scalar(@exists). ") found!"
    if scalar(@exists) > 1;

  my $exists = $exists[0];
  if ( $exists->freesidestatus ) {
    $skip++;
    $param->{skiprow} = 1;
  } else {
    $rep++;
    my $error = $exists->delete;
    return $error if $error;
  }

  return '';

};

my $error = FS::cdr::batch_import( {
  'file'               => $file,
  'format'             => $format,
  'batch_namevalue'    => $file."-REIMPORT$$",
  'preinsert_callback' => $cb,
} );
die $error if $error;

warn "$skip skipped, $rep replaced, $new new\n";

sub usage {
  "Usage: \n  cdr.reimport user format filename\n";
}