+sub replace {
+ my $self = shift;
+
+ 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;
+
+ my $error = $self->SUPER::replace(@_);
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+
+ foreach my $pf ( grep { /^phonetypenum(\d+)$/ && $self->get($_) }
+ keys %{ $self->hashref } ) {
+ $pf =~ /^phonetypenum(\d+)$/ or die "wtf (daily, the)";
+ my $phonetypenum = $1;
+
+ my %cp = ( 'contactnum' => $self->contactnum,
+ 'phonetypenum' => $phonetypenum,
+ );
+ my $contact_phone = qsearchs('contact_phone', \%cp)
+ || new FS::contact_phone \%cp;
+
+ my %cpd = _parse_phonestring( $self->get($pf) );
+ $contact_phone->set( $_ => $cpd{$_} ) foreach keys %cpd;
+
+ my $method = $contact_phone->contactphonenum ? 'replace' : 'insert';
+
+ $error = $contact_phone->$method;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+ }
+
+ if ( defined($self->get('emailaddress')) ) {
+
+ #ineffecient but whatever, how many email addresses can there be?
+
+ foreach my $contact_email ( $self->contact_email ) {
+ my $error = $contact_email->delete;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+ }
+
+ foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
+
+ my $contact_email = new FS::contact_email {
+ 'contactnum' => $self->contactnum,
+ 'emailaddress' => $email,
+ };
+ $error = $contact_email->insert;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+
+ }
+
+ }
+
+ $dbh->commit or die $dbh->errstr if $oldAutoCommit;
+
+ '';
+
+}
+
+#i probably belong in contact_phone.pm
+sub _parse_phonestring {
+ my $value = shift;
+
+ my($countrycode, $extension) = ('1', '');
+
+ #countrycode
+ if ( $value =~ s/^\s*\+\s*(\d+)// ) {
+ $countrycode = $1;
+ } else {
+ $value =~ s/^\s*1//;
+ }
+ #extension
+ if ( $value =~ s/\s*(ext|x)\s*(\d+)\s*$//i ) {
+ $extension = $2;
+ }
+
+ ( 'countrycode' => $countrycode,
+ 'phonenum' => $value,
+ 'extension' => $extension,
+ );
+}