public String createOrUpdateLead()

in extensions/salesforce-connector/services/src/main/java/org/apache/unomi/sfdc/services/internal/SFDCServiceImpl.java [367:490]


    public String createOrUpdateLead(Profile profile) {
        if (!isConnected()) {
            return null;
        }
        // first we must check if an existing contact exists for the profile.
        String unomiIdentifierValue = (String) profile.getProperty(sfdcConfiguration.getUnomiIdentifierField());
        if (isProfileInContacts(unomiIdentifierValue)) {
            LOGGER.info("Contact {}  found in SFDC... No SFDC field value to send, will not send anything to " +
                    "Salesforce. ", unomiIdentifierValue);
            return null;
        }
        // then we must check if an existing lead exists for the profile.
        LOGGER.info("Checking if we have a lead for identifier value {}...", unomiIdentifierValue);
        Set<String> foundExistingSfdcLeadIds = findLeadIdsByIdentifierValue(unomiIdentifierValue);

        Map<String, Object> sfdcLeadFields = new HashMap<>();
        Map<String, Object> existingSfdcLeadFields = new HashMap<>();
        Date sfdcLastModified = null;

        if (foundExistingSfdcLeadIds.size() > 1) {
            // we found multiple leads matching the identifier value !
            LOGGER.warn("Found multiple matching leads for identifier value {}, will use first matching one !",
                    unomiIdentifierValue);
        }

        if (!foundExistingSfdcLeadIds.isEmpty()) {
            LOGGER.info("Found an existing lead, attempting to update it...");
            // we found an existing lead we must update it
            existingSfdcLeadFields = getLead(foundExistingSfdcLeadIds.iterator().next());
            if (existingSfdcLeadFields.get("LastModifiedDate") != null) {
                try {
                    sfdcLastModified = iso8601DateFormat.parse((String) existingSfdcLeadFields.get("LastModifiedDate"));
                } catch (ParseException e) {
                    LOGGER.error("Error parsing date {}", existingSfdcLeadFields.get("LastModifiedDate"), e);
                }
            }
        } else {
            LOGGER.info("No existing lead found.");
        }

        for (String profilePropertyKey : profile.getProperties().keySet()) {
            String sfdcFieldName = sfdcConfiguration.getUnomiToSfdcFieldMappings().get(profilePropertyKey);
            if (sfdcFieldName == null) {
                // we skip unmapped fields
                continue;
            }
            Object unomiPropertyValue = profile.getProperties().get(profilePropertyKey);
            if (existingSfdcLeadFields.get(sfdcFieldName) == null) {
                // we only set the field if it didn't have a value.
                LOGGER.info("Setting SFDC field {} value to {}", sfdcFieldName, unomiPropertyValue);
                sfdcLeadFields.put(sfdcFieldName, unomiPropertyValue);
            } else {
                // current strategy : Unomi field value wins if different from Salesforce value
                // @todo we should probably improve this by tracking last modification dates on profile/lead properties
                Object sfdcLeadFieldValue = existingSfdcLeadFields.get(sfdcFieldName);
                if (!unomiPropertyValue.equals(sfdcLeadFieldValue)) {
                    LOGGER.info("Overwriting SFDC field {} value to {}", sfdcFieldName, unomiPropertyValue);
                    sfdcLeadFields.put(sfdcFieldName, unomiPropertyValue);
                }
            }
        }
        addConsents(profile, sfdcLeadFields);

        if (sfdcLeadFields.isEmpty()) {
            LOGGER.info("No SFDC field value to send, will not send anything to Salesforce.");
            if (foundExistingSfdcLeadIds.isEmpty()) {
                return null;
            } else {
                return foundExistingSfdcLeadIds.iterator().next();
            }
        }

        if (existingSfdcLeadFields.isEmpty()) {
            // if we are creating a lead, let's make sure we have all the mandatory fields before sending the request
            boolean missingMandatoryFields = false;
            for (String leadMandatoryFieldName : sfdcLeadMandatoryFields) {
                if (sfdcLeadFields.get(leadMandatoryFieldName) == null) {
                    LOGGER.warn("Missing mandatory field {}, aborting sending to Salesforce", leadMandatoryFieldName);
                    missingMandatoryFields = true;
                }
            }
            if (missingMandatoryFields) {
                return null;
            }
        }

        String baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/Lead";
        HttpEntityEnclosingRequestBase request = new HttpPost(baseUrl);
        if (!foundExistingSfdcLeadIds.isEmpty()) {
            baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/Lead/" + foundExistingSfdcLeadIds
                    .iterator().next();
            sfdcLeadFields.remove("Id");
            request = new HttpPatch(baseUrl);
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            StringEntity requestEntity = new StringEntity(
                    objectMapper.writeValueAsString(sfdcLeadFields),
                    ContentType.APPLICATION_JSON);
            request.setEntity(requestEntity);
            Object responseObject = handleRequest(request);
            if (responseObject == null) {
                return null;
            }
            if (responseObject instanceof Map) {
                Map<String, Object> responseData = (Map<String, Object>) responseObject;
                if (responseData.get("id") != null) {
                    String sfdcId = (String) responseData.get("id");
                    LOGGER.info("Lead successfully created/updated in Salesforce. sfdcId={}", sfdcId);
                    return sfdcId;
                }
            }
            LOGGER.info("Response received from Salesforce: {}", responseObject);
        } catch (IOException | HttpException e) {
            LOGGER.error("Error creating or updating lead for profile {}", profile, e);
        }

        if (foundExistingSfdcLeadIds.isEmpty()) {
            return null;
        } else {
            return foundExistingSfdcLeadIds.iterator().next();
        }
    }