#!/usr/bin/perl -w
#
# Template for importing legacy customer data

use strict;
use Date::Parse;
use FS::UID qw(adminsuidsetup datasrc);
use FS::Record qw(fields qsearch qsearchs);
use FS::cust_main;
use FS::cust_pkg;
use FS::cust_svc;
use FS::svc_acct;
use FS::pkg_svc;

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

# use these for the imported cust_main records (unless you have these in legacy
# data)
my($agentnum)=4;
my($refnum)=5;

# map from legacy billing data to pkgpart, maps imported field
# LegacyBillingData to pkgpart.  your names and pkgparts will be different
my(%pkgpart)=(
  'Employee'          => 10,
  'Business'          => 11,
  'Individual'        => 12,
  'Basic PPP'         => 13,
  'Slave'             => 14,
  'Co-Located Server' => 15,
  'Virtual Web'       => 16,
  'Perk Mail'         => 17,
  'Credit Hold'       => 18,
);

my($file)="legacy_file";

open(CLIENT,$file) 
  or die "Can't open $file: $!"; 

# put a tab-separated header atop the file, or define @fields
#   (use these names or change them below)
#
# for cust_main
#   custnum - unique
#   last - (name)
#   first - (name)
#   company
#   address1
#   address2
#   city
#   state
#   zip
#   country
#   daytime - (phone)
#   night - (phone)
#   fax
#   payby - CARD, BILL or COMP
#   payinfo - Credit card #, P.O. # or COMP authorization
#   paydate - Expiration
#   tax - 'Y' for tax exempt
# for cust_pkg
#   LegacyBillingData - maps via %pkgpart above to a pkgpart
# for svc_acct
#   username

my($header);
$header=<CLIENT>;
chop $header;
my(@fields)=map { /^\s*(.*[^\s]+)\s*$/; $1 } split(/\t/,$header);
#print join("\n",@fields);

my($error);
my($link,$line)=(0,0);
while (<CLIENT>) {
  chop; 
  next if /^[\s\t]*$/; #skip any blank lines

  #define %svc hash for this record
  my(@record)=split(/\t/);
  my(%svc);
  foreach (@fields) {
    $svc{$_}=shift @record;   
  }

  # might need to massage some data like this
  $svc{'payby'} =~ s/^Credit Card$/CARD/io;
  $svc{'payby'} =~ s/^Check$/BILL/io;
  $svc{'payby'} =~ s/^Cash$/BILL/io;
  $svc{'payby'} =~ s/^$/BILL/o;
  $svc{'First'} =~ s/&/and/go; 
  $svc{'Zip'} =~ s/\s+$//go;

  my($cust_main) = new FS::cust_main ( {
    'custnum'  => $svc{'custnum'},
    'agentnum' => $agentnum,
    'last'     => $svc{'last'},
    'first'    => $svc{'first'},
    'company'  => $svc{'company'},
    'address1' => $svc{'address1'},
    'address2' => $svc{'address2'},
    'city'     => $svc{'city'},
    'state'    => $svc{'state'},
    'zip'      => $svc{'zip'},
    'country'  => $svc{'country'},
    'daytime'  => $svc{'daytime'},
    'night'    => $svc{'night'},
    'fax'      => $svc{'fax'},
    'payby'    => $svc{'payby'},
    'payinfo'  => $svc{'payinfo'},
    'paydate'  => $svc{'paydate'},
    'payname'  => $svc{'payname'},
    'tax'      => $svc{'tax'},
    'refnum'   => $refnum,
  } );

  $error=$cust_main->insert;

  if ( $error ) {
    warn $cust_main->_dump;
    warn map "$_: ". $svc{$_}. "|\n", keys %svc;
    die $error;
  }

  my($cust_pkg)=new FS::cust_pkg ( {
    'custnum' => $svc{'custnum'},
    'pkgpart' => $pkgpart{$svc{'LegacyBillingData'}},
    'setup'   => '', 
    'bill'    => '',
    'susp'    => '',
    'expire'  => '',
    'cancel'  => '',
  } );

  $error=$cust_pkg->insert;
  if ( $error ) {
    warn $svc{'LegacyBillingData'};
    die $error;
  }

  unless ( $svc{'username'} ) {
    warn "Empty login";
  } else {
    #find svc_acct record (imported with bin/svc_acct.import) for this username
    my($svc_acct)=qsearchs('svc_acct',{'username'=>$svc{'username'}});
    unless ( $svc_acct ) {
      warn "username ", $svc{'username'}, " not found\n";
    } else {
      #link to the cust_pkg record we created above

      #find cust_svc record for this svc_acct record
      my($o_cust_svc)=qsearchs('cust_svc',{
        'svcnum' => $svc_acct->svcnum,
        'pkgnum' => '',
      } );
      unless ( $o_cust_svc ) {
        warn "No unlinked cust_svc for svcnum ", $svc_acct->svcnum;
      } else {

        #make sure this svcpart is in pkgpart
        my($pkg_svc)=qsearchs('pkg_svc',{
          'pkgpart'  => $pkgpart{$svc{'LegacyBillingData'}},
          'svcpart'  => $o_cust_svc->svcpart,
          'quantity' => 1,
        });
        unless ( $pkg_svc ) {
          warn "login ", $svc{'username'}, ": No svcpart ", $o_cust_svc->svcpart,
               " for pkgpart ", $pkgpart{$svc{'Acct. Type'}}, "\n" ;
        } else {

          #create new cust_svc record linked to cust_pkg record 
          my($n_cust_svc) = new FS::cust_svc ({
            'svcnum'  => $o_cust_svc->svcnum,
            'pkgnum'  => $cust_pkg->pkgnum,
            'svcpart' => $pkg_svc->svcpart,
          });
          my($error) = $n_cust_svc->replace($o_cust_svc);
          die $error if $error;
          $link++;
        }
      }
    }
  }

  $line++;

}

warn "\n$link of $line lines linked\n";

# ---

sub usage {
  die "Usage:\n\n  cust_main.import user\n";
}