fd3e9d770dd8a4ac171fdf5784d7f5062b27f091
[freeside.git] / FS / FS / contact.pm
1 package FS::contact;
2 use base qw( FS::Password_Mixin
3              FS::Record );
4
5 use strict;
6 use vars qw( $skip_fuzzyfiles );
7 use Carp;
8 use Scalar::Util qw( blessed );
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::Cursor;
11 use FS::contact_phone;
12 use FS::contact_email;
13 use FS::queue;
14 use FS::phone_type; #for cgi_contact_fields
15 use FS::cust_contact;
16 use FS::prospect_contact;
17
18 $skip_fuzzyfiles = 0;
19
20 =head1 NAME
21
22 FS::contact - Object methods for contact records
23
24 =head1 SYNOPSIS
25
26   use FS::contact;
27
28   $record = new FS::contact \%hash;
29   $record = new FS::contact { 'column' => 'value' };
30
31   $error = $record->insert;
32
33   $error = $new_record->replace($old_record);
34
35   $error = $record->delete;
36
37   $error = $record->check;
38
39 =head1 DESCRIPTION
40
41 An FS::contact object represents an specific contact person for a prospect or
42 customer.  FS::contact inherits from FS::Record.  The following fields are
43 currently supported:
44
45 =over 4
46
47 =item contactnum
48
49 primary key
50
51 =item prospectnum
52
53 prospectnum
54
55 =item custnum
56
57 custnum
58
59 =item locationnum
60
61 locationnum
62
63 =item last
64
65 last
66
67 =item first
68
69 first
70
71 =item title
72
73 title
74
75 =item comment
76
77 comment
78
79 =item selfservice_access
80
81 empty or Y
82
83 =item _password
84
85 =item _password_encoding
86
87 empty or bcrypt
88
89 =item disabled
90
91 disabled
92
93 =back
94
95 =head1 METHODS
96
97 =over 4
98
99 =item new HASHREF
100
101 Creates a new contact.  To add the contact to the database, see L<"insert">.
102
103 Note that this stores the hash reference, not a distinct copy of the hash it
104 points to.  You can ask the object for a copy with the I<hash> method.
105
106 =cut
107
108 sub table { 'contact'; }
109
110 =item insert
111
112 Adds this record to the database.  If there is an error, returns the error,
113 otherwise returns false.
114
115 If the object has an C<emailaddress> field, L<FS::contact_email> records
116 will be created for each (comma-separated) email address in that field. If
117 any of these coincide with an existing email address, this contact will be
118 merged with the contact with that address.
119
120 Then, if the object has any fields named C<phonetypenumN> an
121 L<FS::contact_phone> record will be created for each of them. Those fields
122 should contain phone numbers of the appropriate types (where N is the key of
123 an L<FS::phone_type> record identifying the type of number: daytime, night,
124 etc.).
125
126 After inserting the record, if the object has a 'custnum' or 'prospectnum'
127 field, an L<FS::cust_contact> or L<FS::prospect_contact> record will be
128 created to link the contact to the customer. The following fields will also
129 be included in that record, if they are set on the object:
130 - classnum
131 - comment
132 - selfservice_access
133 - invoice_dest
134
135 =cut
136
137 sub insert {
138   my $self = shift;
139
140   local $SIG{INT} = 'IGNORE';
141   local $SIG{QUIT} = 'IGNORE';
142   local $SIG{TERM} = 'IGNORE';
143   local $SIG{TSTP} = 'IGNORE';
144   local $SIG{PIPE} = 'IGNORE';
145
146   my $oldAutoCommit = $FS::UID::AutoCommit;
147   local $FS::UID::AutoCommit = 0;
148   my $dbh = dbh;
149
150   #save off and blank values that move to cust_contact / prospect_contact now
151   my $prospectnum = $self->prospectnum;
152   $self->prospectnum('');
153   my $custnum = $self->custnum;
154   $self->custnum('');
155
156   my %link_hash = ();
157   for (qw( classnum comment selfservice_access invoice_dest )) {
158     $link_hash{$_} = $self->get($_);
159     $self->$_('');
160   }
161
162   #look for an existing contact with this email address
163   my $existing_contact = '';
164   if ( $self->get('emailaddress') =~ /\S/ ) {
165   
166     my %existing_contact = ();
167
168     foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
169  
170       my $contact_email = qsearchs('contact_email', { emailaddress=>$email } )
171         or next;
172
173       my $contact = $contact_email->contact;
174       $existing_contact{ $contact->contactnum } = $contact;
175
176     }
177
178     if ( scalar( keys %existing_contact ) > 1 ) {
179       $dbh->rollback if $oldAutoCommit;
180       return 'Multiple email addresses specified '.
181              ' that already belong to separate contacts';
182     } elsif ( scalar( keys %existing_contact ) ) {
183       ($existing_contact) = values %existing_contact;
184     }
185
186   }
187
188   my $error;
189   if ( $existing_contact ) {
190
191     $self->$_($existing_contact->$_())
192       for qw( contactnum _password _password_encoding );
193     $error = $self->SUPER::replace($existing_contact);
194
195   } else {
196
197     $error = $self->SUPER::insert;
198
199   }
200
201   $error ||= $self->insert_password_history;
202
203   if ( $error ) {
204     $dbh->rollback if $oldAutoCommit;
205     return $error;
206   }
207
208   my $cust_contact = '';
209   # if $self->custnum was set, then the customer-specific properties
210   # (custnum, classnum, invoice_dest, selfservice_access, comment) are in
211   # pseudo-fields, and are now in %link_hash. otherwise, ignore all those
212   # fields.
213   if ( $custnum ) {
214     my %hash = ( 'contactnum' => $self->contactnum,
215                  'custnum'    => $custnum,
216                );
217     $cust_contact =  qsearchs('cust_contact', \%hash )
218                   || new FS::cust_contact { %hash, %link_hash };
219     my $error = $cust_contact->custcontactnum ? $cust_contact->replace
220                                               : $cust_contact->insert;
221     if ( $error ) {
222       $dbh->rollback if $oldAutoCommit;
223       return $error;
224     }
225   }
226
227   if ( $prospectnum ) {
228     my %hash = ( 'contactnum'  => $self->contactnum,
229                  'prospectnum' => $prospectnum,
230                );
231     my $prospect_contact =  qsearchs('prospect_contact', \%hash )
232                          || new FS::prospect_contact { %hash, %link_hash };
233     my $error =
234       $prospect_contact->prospectcontactnum ? $prospect_contact->replace
235                                             : $prospect_contact->insert;
236     if ( $error ) {
237       $dbh->rollback if $oldAutoCommit;
238       return $error;
239     }
240   }
241
242   foreach my $pf ( grep { /^phonetypenum(\d+)$/ && $self->get($_) =~ /\S/ }
243                         keys %{ $self->hashref } ) {
244     $pf =~ /^phonetypenum(\d+)$/ or die "wtf (daily, the)";
245     my $phonetypenum = $1;
246
247     my %hash = ( 'contactnum'   => $self->contactnum,
248                  'phonetypenum' => $phonetypenum,
249                );
250     my $contact_phone =
251       qsearchs('contact_phone', \%hash)
252         || new FS::contact_phone { %hash, _parse_phonestring($self->get($pf)) };
253     my $error = $contact_phone->contactphonenum ? $contact_phone->replace
254                                                 : $contact_phone->insert;
255     if ( $error ) {
256       $dbh->rollback if $oldAutoCommit;
257       return $error;
258     }
259   }
260
261   if ( $self->get('emailaddress') =~ /\S/ ) {
262
263     foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
264       my %hash = (
265         'contactnum'   => $self->contactnum,
266         'emailaddress' => $email,
267       );
268       unless ( qsearchs('contact_email', \%hash) ) {
269         my $contact_email = new FS::contact_email \%hash;
270         my $error = $contact_email->insert;
271         if ( $error ) {
272           $dbh->rollback if $oldAutoCommit;
273           return $error;
274         }
275       }
276     }
277
278   }
279
280   unless ( $skip_fuzzyfiles ) { #unless ( $import || $skip_fuzzyfiles ) {
281     #warn "  queueing fuzzyfiles update\n"
282     #  if $DEBUG > 1;
283     my $error = $self->queue_fuzzyfiles_update;
284     if ( $error ) {
285       $dbh->rollback if $oldAutoCommit;
286       return "updating fuzzy search cache: $error";
287     }
288   }
289
290   if (      $link_hash{'selfservice_access'} eq 'R'
291        or ( $link_hash{'selfservice_access'}
292             && $cust_contact
293             && ! length($self->_password)
294           )
295      )
296   {
297     my $error = $self->send_reset_email( queue=>1 );
298     if ( $error ) {
299       $dbh->rollback if $oldAutoCommit;
300       return $error;
301     }
302   }
303
304   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
305
306   '';
307
308 }
309
310 =item delete
311
312 Delete this record from the database.
313
314 =cut
315
316 sub delete {
317   my $self = shift;
318
319   local $SIG{HUP} = 'IGNORE';
320   local $SIG{INT} = 'IGNORE';
321   local $SIG{QUIT} = 'IGNORE';
322   local $SIG{TERM} = 'IGNORE';
323   local $SIG{TSTP} = 'IGNORE';
324   local $SIG{PIPE} = 'IGNORE';
325
326   my $oldAutoCommit = $FS::UID::AutoCommit;
327   local $FS::UID::AutoCommit = 0;
328   my $dbh = dbh;
329
330   #got a prospetnum or custnum? delete the prospect_contact or cust_contact link
331
332   if ( $self->prospectnum ) {
333     my $prospect_contact = qsearchs('prospect_contact', {
334                              'contactnum'  => $self->contactnum,
335                              'prospectnum' => $self->prospectnum,
336                            });
337     my $error = $prospect_contact->delete;
338     if ( $error ) {
339       $dbh->rollback if $oldAutoCommit;
340       return $error;
341     }
342   }
343
344   # if $self->custnum was set, then we're removing the contact from this
345   # customer.
346   if ( $self->custnum ) {
347     my $cust_contact = qsearchs('cust_contact', {
348                          'contactnum'  => $self->contactnum,
349                          'custnum' => $self->custnum,
350                        });
351     my $error = $cust_contact->delete;
352     if ( $error ) {
353       $dbh->rollback if $oldAutoCommit;
354       return $error;
355     }
356   }
357
358   # then, proceed with deletion only if the contact isn't attached to any other
359   # prospects or customers
360
361   #inefficient, but how many prospects/customers can a single contact be
362   # attached too?  (and is removing them from one a common operation?)
363   if ( $self->prospect_contact || $self->cust_contact ) {
364     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
365     return '';
366   }
367
368   #proceed with deletion
369
370   foreach my $cust_pkg ( $self->cust_pkg ) {
371     $cust_pkg->contactnum('');
372     my $error = $cust_pkg->replace;
373     if ( $error ) {
374       $dbh->rollback if $oldAutoCommit;
375       return $error;
376     }
377   }
378
379   foreach my $object ( $self->contact_phone, $self->contact_email ) {
380     my $error = $object->delete;
381     if ( $error ) {
382       $dbh->rollback if $oldAutoCommit;
383       return $error;
384     }
385   }
386
387   my $error = $self->delete_password_history
388            || $self->SUPER::delete;
389   if ( $error ) {
390     $dbh->rollback if $oldAutoCommit;
391     return $error;
392   }
393
394   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
395   '';
396
397 }
398
399 =item replace OLD_RECORD
400
401 Replaces the OLD_RECORD with this one in the database.  If there is an error,
402 returns the error, otherwise returns false.
403
404 =cut
405
406 sub replace {
407   my $self = shift;
408
409   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
410               ? shift
411               : $self->replace_old;
412
413   $self->$_( $self->$_ || $old->$_ ) for qw( _password _password_encoding );
414
415   local $SIG{INT} = 'IGNORE';
416   local $SIG{QUIT} = 'IGNORE';
417   local $SIG{TERM} = 'IGNORE';
418   local $SIG{TSTP} = 'IGNORE';
419   local $SIG{PIPE} = 'IGNORE';
420
421   my $oldAutoCommit = $FS::UID::AutoCommit;
422   local $FS::UID::AutoCommit = 0;
423   my $dbh = dbh;
424
425   #save off and blank values that move to cust_contact / prospect_contact now
426   my $prospectnum = $self->prospectnum;
427   $self->prospectnum('');
428   my $custnum = $self->custnum;
429   $self->custnum('');
430
431   my %link_hash = ();
432   for (qw( classnum comment selfservice_access invoice_dest )) {
433     $link_hash{$_} = $self->get($_);
434     $self->$_('');
435   }
436
437   my $error = $self->SUPER::replace($old);
438   if ( $old->_password ne $self->_password ) {
439     $error ||= $self->insert_password_history;
440   }
441   if ( $error ) {
442     $dbh->rollback if $oldAutoCommit;
443     return $error;
444   }
445
446   my $cust_contact = '';
447   # if $self->custnum was set, then the customer-specific properties
448   # (custnum, classnum, invoice_dest, selfservice_access, comment) are in
449   # pseudo-fields, and are now in %link_hash. otherwise, ignore all those
450   # fields.
451   if ( $custnum ) {
452     my %hash = ( 'contactnum' => $self->contactnum,
453                  'custnum'    => $custnum,
454                );
455     my $error;
456     if ( $cust_contact = qsearchs('cust_contact', \%hash ) ) {
457       $cust_contact->$_($link_hash{$_}) for keys %link_hash;
458       $error = $cust_contact->replace;
459     } else {
460       $cust_contact = new FS::cust_contact { %hash, %link_hash };
461       $error = $cust_contact->insert;
462     }
463     if ( $error ) {
464       $dbh->rollback if $oldAutoCommit;
465       return $error;
466     }
467   }
468
469   if ( $prospectnum ) {
470     my %hash = ( 'contactnum'  => $self->contactnum,
471                  'prospectnum' => $prospectnum,
472                );
473     my $error;
474     if ( my $prospect_contact = qsearchs('prospect_contact', \%hash ) ) {
475       $prospect_contact->$_($link_hash{$_}) for keys %link_hash;
476       $error = $prospect_contact->replace;
477     } else {
478       my $prospect_contact = new FS::prospect_contact { %hash, %link_hash };
479       $error = $prospect_contact->insert;
480     }
481     if ( $error ) {
482       $dbh->rollback if $oldAutoCommit;
483       return $error;
484     }
485   }
486
487   foreach my $pf ( grep { /^phonetypenum(\d+)$/ }
488                         keys %{ $self->hashref } ) {
489     $pf =~ /^phonetypenum(\d+)$/ or die "wtf (daily, the)";
490     my $phonetypenum = $1;
491
492     my %cp = ( 'contactnum'   => $self->contactnum,
493                'phonetypenum' => $phonetypenum,
494              );
495     my $contact_phone = qsearchs('contact_phone', \%cp);
496
497     my $pv = $self->get($pf);
498         $pv =~ s/\s//g;
499
500     #if new value is empty, delete old entry
501     if (!$pv) {
502       if ($contact_phone) {
503         $error = $contact_phone->delete;
504         if ( $error ) {
505           $dbh->rollback if $oldAutoCommit;
506           return $error;
507         }
508       }
509       next;
510     }
511
512     $contact_phone ||= new FS::contact_phone \%cp;
513
514     my %cpd = _parse_phonestring( $pv );
515     $contact_phone->set( $_ => $cpd{$_} ) foreach keys %cpd;
516
517     my $method = $contact_phone->contactphonenum ? 'replace' : 'insert';
518
519     $error = $contact_phone->$method;
520     if ( $error ) {
521       $dbh->rollback if $oldAutoCommit;
522       return $error;
523     }
524   }
525
526   if ( defined($self->hashref->{'emailaddress'}) ) {
527
528     #ineffecient but whatever, how many email addresses can there be?
529
530     foreach my $contact_email ( $self->contact_email ) {
531       my $error = $contact_email->delete;
532       if ( $error ) {
533         $dbh->rollback if $oldAutoCommit;
534         return $error;
535       }
536     }
537
538     foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
539  
540       my $contact_email = new FS::contact_email {
541         'contactnum'   => $self->contactnum,
542         'emailaddress' => $email,
543       };
544       $error = $contact_email->insert;
545       if ( $error ) {
546         $dbh->rollback if $oldAutoCommit;
547         return $error;
548       }
549
550     }
551
552   }
553
554   unless ( $skip_fuzzyfiles ) { #unless ( $import || $skip_fuzzyfiles ) {
555     #warn "  queueing fuzzyfiles update\n"
556     #  if $DEBUG > 1;
557     $error = $self->queue_fuzzyfiles_update;
558     if ( $error ) {
559       $dbh->rollback if $oldAutoCommit;
560       return "updating fuzzy search cache: $error";
561     }
562   }
563
564   if ( $cust_contact and (
565                               (      $cust_contact->selfservice_access eq ''
566                                   && $link_hash{selfservice_access}
567                                   && ! length($self->_password)
568                               )
569                            || $cust_contact->_resend()
570                          )
571     )
572   {
573     my $error = $self->send_reset_email( queue=>1 );
574     if ( $error ) {
575       $dbh->rollback if $oldAutoCommit;
576       return $error;
577     }
578   }
579
580   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
581
582   '';
583
584 }
585
586 =item _parse_phonestring PHONENUMBER_STRING
587
588 Subroutine, takes a string and returns a list (suitable for assigning to a hash)
589 with keys 'countrycode', 'phonenum' and 'extension'
590
591 (Should probably be moved to contact_phone.pm, hence the initial underscore.)
592
593 =cut
594
595 sub _parse_phonestring {
596   my $value = shift;
597
598   my($countrycode, $extension) = ('1', '');
599
600   #countrycode
601   if ( $value =~ s/^\s*\+\s*(\d+)// ) {
602     $countrycode = $1;
603   } else {
604     $value =~ s/^\s*1//;
605   }
606   #extension
607   if ( $value =~ s/\s*(ext|x)\s*(\d+)\s*$//i ) {
608      $extension = $2;
609   }
610
611   ( 'countrycode' => $countrycode,
612     'phonenum'    => $value,
613     'extension'   => $extension,
614   );
615 }
616
617 =item queue_fuzzyfiles_update
618
619 Used by insert & replace to update the fuzzy search cache
620
621 =cut
622
623 use FS::cust_main::Search;
624 sub queue_fuzzyfiles_update {
625   my $self = shift;
626
627   local $SIG{HUP} = 'IGNORE';
628   local $SIG{INT} = 'IGNORE';
629   local $SIG{QUIT} = 'IGNORE';
630   local $SIG{TERM} = 'IGNORE';
631   local $SIG{TSTP} = 'IGNORE';
632   local $SIG{PIPE} = 'IGNORE';
633
634   my $oldAutoCommit = $FS::UID::AutoCommit;
635   local $FS::UID::AutoCommit = 0;
636   my $dbh = dbh;
637
638   foreach my $field ( 'first', 'last' ) {
639     my $queue = new FS::queue { 
640       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
641     };
642     my @args = "contact.$field", $self->get($field);
643     my $error = $queue->insert( @args );
644     if ( $error ) {
645       $dbh->rollback if $oldAutoCommit;
646       return "queueing job (transaction rolled back): $error";
647     }
648   }
649
650   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
651   '';
652
653 }
654
655 =item check
656
657 Checks all fields to make sure this is a valid contact.  If there is
658 an error, returns the error, otherwise returns false.  Called by the insert
659 and replace methods.
660
661 =cut
662
663 sub check {
664   my $self = shift;
665
666   if ( $self->selfservice_access eq 'R' ) {
667     $self->selfservice_access('Y');
668     $self->_resend('Y');
669   }
670
671   my $error = 
672     $self->ut_numbern('contactnum')
673     || $self->ut_foreign_keyn('prospectnum', 'prospect_main', 'prospectnum')
674     || $self->ut_foreign_keyn('custnum',     'cust_main',     'custnum')
675     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
676     || $self->ut_foreign_keyn('classnum',    'contact_class', 'classnum')
677     || $self->ut_namen('last')
678     || $self->ut_namen('first')
679     || $self->ut_textn('title')
680     || $self->ut_textn('comment')
681     || $self->ut_enum('selfservice_access', [ '', 'Y' ])
682     || $self->ut_textn('_password')
683     || $self->ut_enum('_password_encoding', [ '', 'bcrypt'])
684     || $self->ut_enum('disabled', [ '', 'Y' ])
685   ;
686   return $error if $error;
687
688   return "Prospect and customer!"       if $self->prospectnum && $self->custnum;
689
690   return "One of first name, last name, or title must have a value"
691     if ! grep $self->$_(), qw( first last title);
692
693   $self->SUPER::check;
694 }
695
696 =item line
697
698 Returns a formatted string representing this contact, including name, title and
699 comment.
700
701 =cut
702
703 sub line {
704   my $self = shift;
705   my $data = $self->first. ' '. $self->last;
706   $data .= ', '. $self->title
707     if $self->title;
708   $data .= ' ('. $self->comment. ')'
709     if $self->comment;
710   $data;
711 }
712
713 =item firstlast
714
715 Returns a formatted string representing this contact, with just the name.
716
717 =cut
718
719 sub firstlast {
720   my $self = shift;
721   $self->first . ' ' . $self->last;
722 }
723
724 #=item contact_classname PROSPECT_OBJ | CUST_MAIN_OBJ
725 #
726 #Returns the name of this contact's class for the specified prospect or
727 #customer (see L<FS::prospect_contact>, L<FS::cust_contact> and
728 #L<FS::contact_class>).
729 #
730 #=cut
731 #
732 #sub contact_classname {
733 #  my( $self, $prospect_or_cust ) = @_;
734 #
735 #  my $link = '';
736 #  if ( ref($prospect_or_cust) eq 'FS::prospect_main' ) {
737 #    $link = qsearchs('prospect_contact', {
738 #              'contactnum'  => $self->contactnum,
739 #              'prospectnum' => $prospect_or_cust->prospectnum,
740 #            });
741 #  } elsif ( ref($prospect_or_cust) eq 'FS::cust_main' ) {
742 #    $link = qsearchs('cust_contact', {
743 #              'contactnum'  => $self->contactnum,
744 #              'custnum'     => $prospect_or_cust->custnum,
745 #            });
746 #  } else {
747 #    croak "$prospect_or_cust is not an FS::prospect_main or FS::cust_main object";
748 #  }
749 #
750 #  my $contact_class = $link->contact_class or return '';
751 #  $contact_class->classname;
752 #}
753
754 =item by_selfservice_email EMAILADDRESS
755
756 Alternate search constructor (class method).  Given an email address, returns
757 the contact for that address. If that contact doesn't have selfservice access,
758 or there isn't one, returns the empty string.
759
760 =cut
761
762 sub by_selfservice_email {
763   my($class, $email) = @_;
764
765   my $contact_email = qsearchs({
766     'table'     => 'contact_email',
767     'addl_from' => ' LEFT JOIN contact USING ( contactnum ) ',
768     'hashref'   => { 'emailaddress' => $email, },
769     'extra_sql' => " AND ( contact.disabled IS NULL ) ".
770                    " AND ( contact.selfservice_access = 'Y' )",
771   }) or return '';
772
773   $contact_email->contact;
774
775 }
776
777 #these three functions are very much false laziness w/FS/FS/Auth/internal.pm
778 # and should maybe be libraried in some way for other password needs
779
780 use Crypt::Eksblowfish::Bcrypt qw( bcrypt_hash en_base64 de_base64);
781
782 sub authenticate_password {
783   my($self, $check_password) = @_;
784
785   if ( $self->_password_encoding eq 'bcrypt' ) {
786
787     my( $cost, $salt, $hash ) = split(',', $self->_password);
788
789     my $check_hash = en_base64( bcrypt_hash( { key_nul => 1,
790                                                cost    => $cost,
791                                                salt    => de_base64($salt),
792                                              },
793                                              $check_password
794                                            )
795                               );
796
797     $hash eq $check_hash;
798
799   } else { 
800
801     return 0 if $self->_password eq '';
802
803     $self->_password eq $check_password;
804
805   }
806
807 }
808
809 =item change_password NEW_PASSWORD
810
811 Changes the contact's selfservice access password to NEW_PASSWORD. This does
812 not check password policy rules (see C<is_password_allowed>) and will return
813 an error only if editing the record fails for some reason.
814
815 If NEW_PASSWORD is the same as the existing password, this does nothing.
816
817 =cut
818
819 sub change_password {
820   my($self, $new_password) = @_;
821
822   # do nothing if the password is unchanged
823   return if $self->authenticate_password($new_password);
824
825   $self->change_password_fields( $new_password );
826
827   $self->replace;
828
829 }
830
831 sub change_password_fields {
832   my($self, $new_password) = @_;
833
834   $self->_password_encoding('bcrypt');
835
836   my $cost = 8;
837
838   my $salt = pack( 'C*', map int(rand(256)), 1..16 );
839
840   my $hash = bcrypt_hash( { key_nul => 1,
841                             cost    => $cost,
842                             salt    => $salt,
843                           },
844                           $new_password,
845                         );
846
847   $self->_password(
848     join(',', $cost, en_base64($salt), en_base64($hash) )
849   );
850
851 }
852
853 # end of false laziness w/FS/FS/Auth/internal.pm
854
855
856 #false laziness w/ClientAPI/MyAccount/reset_passwd
857 use Digest::SHA qw(sha512_hex);
858 use FS::Conf;
859 use FS::ClientAPI_SessionCache;
860 sub send_reset_email {
861   my( $self, %opt ) = @_;
862
863   my @contact_email = $self->contact_email or return '';
864
865   my $reset_session = {
866     'contactnum' => $self->contactnum,
867     'svcnum'     => $opt{'svcnum'},
868   };
869
870   my $timeout = '24 hours'; #?
871
872   my $reset_session_id;
873   do {
874     $reset_session_id = sha512_hex(time(). {}. rand(). $$)
875   } until ( ! defined $self->myaccount_cache->get("reset_passwd_$reset_session_id") );
876     #just in case
877
878   $self->myaccount_cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
879
880   #email it
881
882   my $conf = new FS::Conf;
883
884   my $cust_main = '';
885   my @cust_contact = grep $_->selfservice_access, $self->cust_contact;
886   $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
887
888   my $agentnum = $cust_main ? $cust_main->agentnum : '';
889   my $msgnum = $conf->config('selfservice-password_reset_msgnum', $agentnum);
890   #die "selfservice-password_reset_msgnum unset" unless $msgnum;
891   return "selfservice-password_reset_msgnum unset" unless $msgnum;
892   my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
893   return "selfservice-password_reset_msgnum cannot be loaded" unless $msg_template;
894   my %msg_template = (
895     'to'            => join(',', map $_->emailaddress, @contact_email ),
896     'cust_main'     => $cust_main,
897     'object'        => $self,
898     'substitutions' => { 'session_id' => $reset_session_id }
899   );
900
901   if ( $opt{'queue'} ) { #or should queueing just be the default?
902
903     my $cust_msg = $msg_template->prepare( %msg_template );
904     my $error = $cust_msg->insert;
905     return $error if $error;
906     my $queue = new FS::queue {
907       'job'     => 'FS::cust_msg::process_send',
908       'custnum' => $cust_main ? $cust_main->custnum : '',
909     };
910     $queue->insert( $cust_msg->custmsgnum );
911
912   } else {
913
914     $msg_template->send( %msg_template );
915
916   }
917
918 }
919
920 use vars qw( $myaccount_cache );
921 sub myaccount_cache {
922   #my $class = shift;
923   $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
924                          'namespace' => 'FS::ClientAPI::MyAccount',
925                        } );
926 }
927
928 =item cgi_contact_fields
929
930 Returns a list reference containing the set of contact fields used in the web
931 interface for one-line editing (i.e. excluding contactnum, prospectnum, custnum
932 and locationnum, as well as password fields, but including fields for
933 contact_email and contact_phone records.)
934
935 =cut
936
937 sub cgi_contact_fields {
938   #my $class = shift;
939
940   my @contact_fields = qw(
941     classnum first last title comment emailaddress selfservice_access
942     invoice_dest
943   );
944
945   push @contact_fields, 'phonetypenum'. $_->phonetypenum
946     foreach qsearch({table=>'phone_type', order_by=>'weight'});
947
948   \@contact_fields;
949
950 }
951
952 use FS::upgrade_journal;
953 sub _upgrade_data { #class method
954   my ($class, %opts) = @_;
955
956   # before anything else, migrate contact.custnum to cust_contact records
957   unless ( FS::upgrade_journal->is_done('contact_invoice_dest') ) {
958
959     local($skip_fuzzyfiles) = 1;
960
961     foreach my $contact (qsearch('contact', {})) {
962       my $error = $contact->replace;
963       die $error if $error;
964     }
965
966     FS::upgrade_journal->set_done('contact_invoice_dest');
967   }
968
969
970   # always migrate cust_main_invoice records over
971   local $FS::cust_main::import = 1; # override require_phone and such
972   my $search = FS::Cursor->new('cust_main_invoice', {});
973   my %custnum_dest;
974   while (my $cust_main_invoice = $search->fetch) {
975     my $custnum = $cust_main_invoice->custnum;
976     my $dest = $cust_main_invoice->dest;
977     my $cust_main = $cust_main_invoice->cust_main;
978
979     if ( $dest =~ /^\d+$/ ) {
980       my $svc_acct = FS::svc_acct->by_key($dest);
981       die "custnum $custnum, invoice destination svcnum $svc_acct does not exist\n"
982         if !$svc_acct;
983       $dest = $svc_acct->email;
984     }
985     push @{ $custnum_dest{$custnum} ||= [] }, $dest;
986
987     my $error = $cust_main_invoice->delete;
988     if ( $error ) {
989       die "custnum $custnum, cleaning up cust_main_invoice: $error\n";
990     }
991   }
992
993   foreach my $custnum (keys %custnum_dest) {
994     my $dests = $custnum_dest{$custnum};
995     my $cust_main = FS::cust_main->by_key($custnum);
996     my $error = $cust_main->replace( invoicing_list => $dests );
997     if ( $error ) {
998       die "custnum $custnum, creating contact: $error\n";
999     }
1000   }
1001
1002 }
1003
1004 =back
1005
1006 =head1 BUGS
1007
1008 =head1 SEE ALSO
1009
1010 L<FS::Record>, schema.html from the base documentation.
1011
1012 =cut
1013
1014 1;
1015