2
0

phone.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package model
  2. import (
  3. "fmt"
  4. "github.com/gshopify/service-wrapper/model"
  5. "github.com/mitchellh/mapstructure"
  6. "github.com/nyaruka/phonenumbers"
  7. )
  8. type Phone struct {
  9. number *phonenumbers.PhoneNumber
  10. Verified bool `mapstructure:"phone_verified"`
  11. PhoneNumber string `mapstructure:"phone_number"`
  12. PhoneRegion string `mapstructure:"phone_region"`
  13. }
  14. func ParsePhoneNumber(m map[string]any) (*Phone, error) {
  15. p := Phone{}
  16. if err := mapstructure.Decode(m, &p); err != nil {
  17. return nil, err
  18. }
  19. return NewPhoneNumber(p.PhoneNumber, p.PhoneRegion, p.Verified)
  20. }
  21. func NewPhoneNumber(number, region string, verified bool) (*Phone, error) {
  22. var (
  23. p = Phone{
  24. PhoneNumber: number,
  25. PhoneRegion: region,
  26. Verified: verified,
  27. }
  28. err error
  29. )
  30. if p.PhoneNumber == "" || p.PhoneRegion == "" {
  31. return nil, nil
  32. }
  33. if r := model.CountryCode(p.PhoneRegion); !r.IsValid() {
  34. return nil, fmt.Errorf("illegal country code: `%s`", p.PhoneRegion)
  35. }
  36. p.number, err = phonenumbers.Parse(p.PhoneNumber, p.PhoneRegion)
  37. if err != nil {
  38. return nil, err
  39. }
  40. if p.number.CountryCode != nil {
  41. if cc := phonenumbers.GetRegionCodeForCountryCode(int(*p.number.CountryCode)); cc != p.PhoneRegion {
  42. p.PhoneRegion = cc
  43. }
  44. }
  45. return &p, nil
  46. }
  47. func (p *Phone) String() string {
  48. return phonenumbers.Format(p.number, phonenumbers.INTERNATIONAL)
  49. }