diff --git a/crmEntity.go b/crmEntity.go index 16f5097..a57b470 100644 --- a/crmEntity.go +++ b/crmEntity.go @@ -158,12 +158,12 @@ func crmSearchEntity(entityType string, filters []crmdSearchFilter) (result crmd req.URL.RawQuery = q.Encode() - debugDumpHTTPRequest(req) + //debugDumpHTTPRequest(req) client := &http.Client{} r, err := client.Do(req) - debugDumpHTTPResponse(r) + //debugDumpHTTPResponse(r) if err != nil { return @@ -207,3 +207,25 @@ func crmFindEntityByID(entityType string, id string) (entity interface{}, err er } return } + +func crmFindEntityByAttr(entityType, attribute, value string) (total int, list interface{}, err error) { + filters := []crmdSearchFilter{ + {attribute, "equals", value}, + } + + cs, err := crmSearchEntity(entityType, filters) + if err != nil || cs.Total < 1 { + return + } + total = cs.Total + switch entityType { + case "Lead": + e := []crmdLead{} + err = json.Unmarshal(*cs.List, &e) + list = e + case "Account": + return + + } + return +} diff --git a/crmEntity_test.go b/crmEntity_test.go index 8efa34e..7ff713e 100644 --- a/crmEntity_test.go +++ b/crmEntity_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "fmt" "log" "testing" "time" @@ -161,3 +162,37 @@ func TestDeleteNonExistRecord(t *testing.T) { AssertEqual(t, deleted, false, "deleting non-exist record should be false") } + +func TestSearchByAttr(t *testing.T) { + ids := []string{} + + for i := 0; i < 10; i++ { + e := crmdLead{} + e.FirstName = fmt.Sprintf("%s-%d-%s", "ff", i, time.Now().Format("2006-Jan-02 03:04:05")) + e.LastName = fmt.Sprintf("%s-%d", "ll", i) + e.Password = fmt.Sprintf("%s-pp-%d", "pp", i) + e.Status = "New" + e.EmailAddress = fmt.Sprintf("abc%d@gmail.com", i) + e.WechatHitxyID = fmt.Sprintf("someopenid-%d", i) + b, _ := json.Marshal(e) + entity, _ := crmCreateEntity("Lead", b) + ids = append(ids, entity.(crmdLead).ID) + log.Printf("creating %s", ids[i]) + } + + //search + for i := 0; i < 10; i++ { + log.Printf("trying to match %d , %s", i, ids[i]) + total, list, err := crmFindEntityByAttr("Lead", "emailAddress", fmt.Sprintf("abc%d@gmail.com", i)) + result := list.([]crmdLead) + AssertEqual(t, err, nil, "find by attr should have no error") + AssertEqual(t, total, 1, "should have found 1 and only 1") + AssertEqual(t, len(result), 1, "list should be 1 ") + AssertEqual(t, result[0].ID, ids[i], "the id should be correct.") + } + + for i := 0; i < 10; i++ { + crmDeleteEntity("Lead", ids[i]) + log.Printf("deleting %s", ids[i]) + } +}